How to convert Object with Properties to JSON without “_” in Python 3?

前端 未结 3 1683
别跟我提以往
别跟我提以往 2021-01-12 12:57

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()

3条回答
  •  悲哀的现实
    2021-01-12 13:48

    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.

提交回复
热议问题