How can I include private attributes in my ujson dump?

241 Views Asked by At

I want to dump my Python object at certain points in time for troubleshooting. I am trying to use ujson to dump the object into a file. However, only the public attributes in my object are getting written into the file. The protected attributes are ignored.

Here is an IPython code snippet trying to explain the problem:

In [49]: class Harlog: 
    ...:     def __init__(self): 
    ...:         self.a = 1 
    ...:         self.b = 2 
    ...:         self.c = 3 
    ...:         self._d = 4 
    ...:                                                                                                                                                                                                        

In [50]: harlog = HarLog()                                                                                                                                                                                      

In [51]: vars(harlog)                                                                                                                                                                                           
Out[51]: {}

In [52]: ujson.dumps(harlog)                                                                                                                                                                                    
Out[52]: '{"a":1,"b":2,"c":3}'

Notice that the protected attribute '_d' was not serialized as part of the dump.

Looking for reasons behind this and if there is a way to serialize protected members as well.

1

There are 1 best solutions below

0
On

You can use this below:

class Harlog:

    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3
        self._d = 4

    def json_converter(self):
        return json.dumps(self, default=lambda o: {key.lstrip('_'): value for key, value in o.__dict__.items()})

and call your class below like this:

harlog = Harlog()
print(harlog.json_converter())