如何在不带"_"的情况下将具有属性的对象转换为JSON在Python 3中? [英] How to convert Object with Properties to JSON without "_" in Python 3?
问题描述
我想将Python对象转换为JSON格式.
I would like to convert an Python object into JSON-format.
User 类的私有属性是使用属性定义的.我在此处找到方法 to_Json()
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
}
摆脱JSON格式下划线的最简单方法是什么? (我希望使用名称"而不是"_name".)由于我遇到错误(最大递归深度),因此无法删除类中的下划线.我认为重命名属性的方法可以解决此问题,但这是最好的解决方案吗?
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?
重命名json.dumbs之前的所有键(请参见此处)是不切实际的方法,因为我的课比上面的例子还要复杂.
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.
那么,将Python对象尽快转换为JSON格式的最佳实践是什么?
So, what is the best practice to convert a Python object into JSON-format as fast as possible?
推荐答案
如果您发布的示例代码反映了您的真实代码,则根本没有任何理由使用该属性.您可以这样做:
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:
class User(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:
class MyEncoder(json.JSONEncoder):
def default(self, o):
return {k.lstrip('_'): v for k, v in vars(o).items()}
json_encoded_user = json.dumps(some_user, cls=MyEncoder)
这篇关于如何在不带"_"的情况下将具有属性的对象转换为JSON在Python 3中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!