简体   繁体   English

在Python中将自定义对象序列化为JSON的方法

[英]Method to serialize custom object to JSON in Python

Generally, we can define __str__ method to make str(obj) return what we want. 通常,我们可以定义__str__方法使str(obj)返回我们想要的。

But now I want to define my Model object to return a default JSON string when using json.dumps(obj) . 但是现在我想定义我的Model对象以在使用json.dumps(obj)时返回默认的JSON字符串。

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__)

If you only need Python -> JSON, it's simple to write a JSONEncoder class that calls such a method for any object: 如果你只需要Python - > JSON,那么编写一个为任何对象调用这样一个方法的JSONEncoder类很简单:

class AutoJSONEncoder(JSONEncoder):
    def default(self, obj):
        try:
            return obj._json()
        except AttributeError:
            return JSONEncoder.default(self, obj)

You can then use the class directly AutoJSONEncoder().encode(obj) or through the dumps interface json.dumps(obj, cls=AutoJSONEncoder) . 然后,您可以直接使用该类AutoJSONEncoder().encode(obj)或通过dumps接口json.dumps(obj, cls=AutoJSONEncoder)

The reverse direction requires at least a list of classes for which to call a _fromjson method. 反方向至少需要一个类列表,可以调用_fromjson方法。

(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.) (注意: __foo__名称是保留的,因此您不应为自己的目的定义它们__bar调用名称修改,这可能不是您想要的。)

import json


class MyEncoder(json.JSONEncoder):
    """
    JSONEncoder subclass that leverages an object's `__json__()` method,
    if available, to obtain its default JSON representation. 

    """
    def default(self, obj):
        if hasattr(obj, '__json__'):
            return obj.__json__()
        return json.JSONEncoder.default(self, obj)


class MyClass(object):
    name = 'John'
    age = 30

    def __json__(self):
        return {'name': self.name, 'age': self.age}

>>> json.dumps(MyClass(), cls=MyEncoder)
{"age": 30, "name": "John"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM