Skip to content Skip to sidebar Skip to footer

How To Convert Object With Properties To Json Without "_" In Python 3?

I would like to convert an Python object into JSON-format. The private attributes of the class User are defined using properties. The method to_Json() I have found here class User

Solution 1:

If the example code you posted mirrors your real code, there really isn't any reason for the properties at all. You could just do:

classUser(object):
    def__init__(self):
        self.name = None
        self.age = None

since you're not really hiding anything from the user behind the underscores and properties anyway.

If you do need to do the transformation, I like to do it in a custom encoder:

classMyEncoder(json.JSONEncoder):
    defdefault(self, o):
        return {k.lstrip('_'): v for k, v invars(o).items()}

json_encoded_user = json.dumps(some_user, cls=MyEncoder)

Solution 2:

In Python, you'd normally not use properties for basic attributes. You'd leave name and age to be directly accessible attributes. There is no need to wrap those in property objects unless you need to transform the data when getting or setting.

If you have good reasons to use attributes with underscores but reflect them as JSON dictionaries, you can transform your dictionary when converting to a dictionary:

object_dict = lambda o: {key.lstrip('_'): value for key, value in o.__dict__.items()}
return json.dumps(self, default=object_dict, allow_nan=False, sort_keys=False, indent=4)

Note that this does nothing to prevent collisions. If you have both a _name and a name attribute on your instance, you'll clobber one or the other.

Solution 3:

I had a similar problem, but I had private fields with two underscore characters.

classUser:
    def__init__(self, id, name):
        self.id = id
        self.name = name

    @propertydefid(self):
        return self.__id    @id.setterdefid(self, id):
        self.__id = id    @propertydefname(self):
        return self.__name

    @name.setterdefname(self, name):
        self.__name = name

Therefore, my json encoder is slightly different

from json import JSONEncoder


defbeautify_key(str):
    index = str.index('__')
    if index <= 0:
        returnstrreturnstr[index + 2:]


classJsonEncoder(JSONEncoder):

    defdefault(self, o):
        return {beautify_key(k): v for k, v invars(o).items()}

Full answer is here.

Post a Comment for "How To Convert Object With Properties To Json Without "_" In Python 3?"