在Python中将自定义对象序列化为JSON的方法 [英] Method to serialize custom object to JSON in Python
问题描述
通常,我们可以定义__str__
方法以使str(obj)
返回我们想要的内容.
Generally, we can define __str__
method to make str(obj)
return what we want.
但是现在我想定义我的Model对象,以便在使用json.dumps(obj)
时返回默认的JSON字符串.
But now I want to define my Model object to return a default JSON string when using json.dumps(obj)
.
我有什么好方法可以在类中声明一个方法来做到这一点吗?
Is there any nice way for me to declare a method in the class to do this?
class MyClass:
...
def __json__(self):
return {'name': self.name, 'age': self.age}
obj = MyClass()
json.dumps(obj) # returns the same as json.dumps(obj.__json__)
推荐答案
如果只需要Python-> JSON,编写一个JSONEncoder类很简单,该类可以对任何对象调用这样的方法:
If you only need Python -> JSON, it's simple to write a JSONEncoder class that calls such a method for any object:
class AutoJSONEncoder(JSONEncoder):
def default(self, obj):
try:
return obj._json()
except AttributeError:
return JSONEncoder.default(self, obj)
然后,您可以直接AutoJSONEncoder().encode(obj)
或通过dumps
界面json.dumps(obj, cls=AutoJSONEncoder)
使用该类.
You can then use the class directly AutoJSONEncoder().encode(obj)
or through the dumps
interface json.dumps(obj, cls=AutoJSONEncoder)
.
相反的方向至少需要一个调用_fromjson
方法的类的列表.
The reverse direction requires at least a list of classes for which to call a _fromjson
method.
(注意:__foo__
名称是保留的,因此您不应出于自己的目的定义它们.__bar
调用名称修饰,这可能不是您想要的.)
(Note: __foo__
names are reserved so you shouldn't define them for your own purposes. __bar
invokes name mangling, which probably isn't what you want.)
这篇关于在Python中将自定义对象序列化为JSON的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!