I would like to serialize users into json. User has only private fields.
user.py
class User:
def __init__(self, id, name):
self. set_id(id)
self.set_name(name)
def set_id(self, id):
self.__id = id
def set_name(self, name):
self.__name = name
json_encoder.py, without it json.dumps
does not work.
from json import JSONEncoder
class JsonEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
user_app.py
import json
from json_encoder import JsonEncoder
from user import User
def main():
users = build_users(names) # a function that returns list of users
users_json = json.dumps(users, indent=4, sort_keys=True, cls=JsonEncoder)
print(users_json)
if __name__ == '__main__':
main()
It prints
[
{
"_User__id": 0,
"_User__name": "Alex"
},
{
"_User__id": 1,
"_User__name": "John"
}
]
Which is almost good. I would like, however, to have private fields as field names - without class name prefix.
[
{
"id": 0,
"name": "Alex"
}
]
Is there annotation, or should I write custom helper to customize json output.
By the way, is it a good practice to make private fields in python? I come from Java world, where we do prefer private fields.
Update
How to make a class JSON serializable partially answers my question. How to serialize it with beautiful properties names, see example of my output, I still have to learn more. I did not know how customize JsonEncoder. I posted my answer.