带有私有字段的json转储 [英] json dumps with private fields
问题描述
我想将用户序列化为json.用户只有私人字段.
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 ,没有它,json.dumps
不起作用.
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()
它打印
[
{
"_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"
}
]
是否有注释,或者我应该编写自定义帮助程序来自定义json输出.
Is there annotation, or should I write custom helper to customize json output.
顺便说一句,在python中创建私有字段是一种好习惯吗?我来自Java世界,在这里我们更喜欢私有字段.
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.
如何使可序列化的JSON类部分回答了我的问题.如何使用漂亮的属性名称对其进行序列化,请参见输出示例,但我仍然需要了解更多信息.我不知道如何自定义 JsonEncoder .我发布了答案.
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.
推荐答案
感谢 jasonharper 到目前为止,我发现<有关属性和设置器的一个href ="https://www.python-course.eu/python3_properties.php" rel ="nofollow noreferrer">示例现在,我知道如何在python中封装.
Thanks to jasonharper So far, I found example about properties and setters Now I know how to do encapsulation in python.
user.py
class User:
def __init__(self, id, name):
self.id = id
self.name = name
@property
def id(self):
return self.__id
@id.setter
def id(self, id):
self.__id = id
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
接下来,我需要将其序列化为JSON .
json_encoder.py
from json import JSONEncoder
def beautify_key(str):
index = str.index('__')
if index <= 0:
return str
return str[index + 2:]
class JsonEncoder(JSONEncoder):
def default(self, o):
return {beautify_key(k): v for k, v in vars(o).items()}
现在输出对我来说是正确的.
Now the output is correct for me.
[
{
"id": 0,
"name": "Alex"
},
{
"id": 1,
"name": "John"
}
]
这篇关于带有私有字段的json转储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!