我试图创建一个类实例的JSON字符串表示,有困难。假设这个类是这样构建的:

class testclass:
    value1 = "a"
    value2 = "b"

对json的调用。转储是这样的:

t = testclass()
json.dumps(t)

它失败了,告诉我测试类不是JSON序列化的。

TypeError: <__main__.testclass object at 0x000000000227A400> is not JSON serializable

我也尝试过使用pickle模块:

t = testclass()
print(pickle.dumps(t, pickle.HIGHEST_PROTOCOL))

它提供类实例的信息,而不是类实例的序列化内容。

b'\x80\x03c__main__\ntestclass\nq\x00)\x81q\x01}q\x02b.'

我做错了什么?


当前回答

还有另一种非常简单和优雅的方法可以应用在这里,那就是只子类'dict',因为它默认是可序列化的。

from json import dumps

class Response(dict):
    def __init__(self, status_code, body):
        super().__init__(
            status_code = status_code,
            body = body
        )

r = Response()
dumps(r)

其他回答

你可以使用Jsonic将几乎任何东西序列化为JSON:

https://github.com/OrrBin/Jsonic

例子:

class TestClass:
def __init__(self):
    self.x = 1
    self.y = 2

instance = TestClass()
s = serialize(instance): # instance s set to: {"x":1, "y":2}
d = deserialize(s) # d is a new class instance of TestClass

Jsonic有一些不错的特性,比如声明类属性为瞬态的和类型安全的反序列化。

(晚了几年才有答案,但我认为这可能会对其他人有所帮助)

这里有一些关于如何开始做这件事的很好的答案。但有一些事情要记住:

如果实例嵌套在大型数据结构中怎么办? 如果还想要类名呢? 如果要反序列化实例该怎么办? 如果你使用__slots__而不是__dict__呢? 如果你只是不想自己动手呢?

json-tricks是一个库(我创建的,其他人贡献的),它已经能够做到这一点很长时间了。例如:

class MyTestCls:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

cls_instance = MyTestCls(s='ub', dct={'7': 7})

json = dumps(cls_instance, indent=4)
instance = loads(json)

您将得到您的实例。这里的json是这样的:

{
    "__instance_type__": [
        "json_tricks.test_class",
        "MyTestCls"
    ],
    "attributes": {
        "s": "ub",
        "dct": {
            "7": 7
        }
    }
}

如果你喜欢自己做解决方案,你可以查看json-tricks的源代码,以免忘记一些特殊情况(如__slots__)。

它也可以处理其他类型,比如numpy数组,datetimes,复数;它还允许注释。

我为此做了一个函数,效果很好:

def serialize(x,*args,**kwargs):
    kwargs.setdefault('default',lambda x:getattr(x,'__dict__',dict((k,getattr(x,k) if not callable(getattr(x,k)) else repr(getattr(x,k))) for k in dir(x) if not (k.startswith('__') or isinstance(getattr(x,k),x.__class__)))))
    return json.dumps(x,*args,**kwargs)

使用任意的可扩展对象,然后将其序列化为JSON:

import json

class Object(object):
    pass

response = Object()
response.debug = []
response.result = Object()

# Any manipulations with the object:
response.debug.append("Debug string here")
response.result.body = "404 Not Found"
response.result.code = 404

# Proper JSON output, with nice formatting:
print(json.dumps(response, indent=4, default=lambda x: x.__dict__))

使用jsonpickle

import jsonpickle

object = YourClass()
json_object = jsonpickle.encode(object)