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:
def __init__(self):
self._name = None
self._gender = None
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def gender(self):
return self._gender
@gender.setter
def gender(self, gender):
self._gender = gender
def to_Json(self):
return json.dumps(self, default=lambda o: o.__dict__, allow_nan=False, sort_keys=False, indent=4)
The output using this class and method is:
{
"_name": "Peter",
"_age": 26
}
What is the easiest way to get rid of the underscores in the JSON-format? (I want "name" instead of "_name") Removing the underscore in the class is not an option since I get an error (max. recursion depth). I think renaming the methods of the attributes would solve this problem, but is this the best solution here?
Renaming all keys before the json.dumbs (see here) is not a practical approach because I my class is more complex than the above example.
So, what is the best practice to convert a Python object into JSON-format as fast as possible?