将类实例序列化为 JSON [英] Serializing class instance to JSON

查看:44
本文介绍了将类实例序列化为 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建类实例的 JSON 字符串表示,但遇到了困难.假设这个类是这样构建的:

I am trying to create a JSON string representation of a class instance and having difficulty. Let's say the class is built like this:

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

对 json.dumps 的调用是这样进行的:

A call to the json.dumps is made like this:

t = testclass()
json.dumps(t)

失败并告诉我测试类不是 JSON 可序列化的.

It is failing and telling me that the testclass is not JSON serializable.

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

我也尝试过使用pickle模块:

I have also tried using the pickle module :

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

它提供类实例信息,但不提供类实例的序列化内容.

And it gives class instance information but not a serialized content of the class instance.

b'x80x03c__main__
testclass
qx00)x81qx01}qx02b.'

我做错了什么?

推荐答案

基本问题是 JSON 编码器 json.dumps() 默认只知道如何序列化有限的一组对象类型,所有内置类型.在这里列出:https://docs.python.org/3.3/library/json.html#encoders-and-decoders

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

一个好的解决方案是让您的类从 JSONEncoder 继承,然后实现 JSONEncoder.default() 函数,并使该函数为您的班级.

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

一个简单的解决方案是对该实例的 .__dict__ 成员调用 json.dumps().这是一个标准的 Python dict,如果您的类很简单,它将是 JSON 可序列化的.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

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

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

本博文中讨论了上述方法:

The above approach is discussed in this blog posting:

序列化使用 _dict_

当然,Python 提供了一个内置函数,可以为您访问 .__dict__,称为 vars().

And, of course, Python offers a built-in function that accesses .__dict__ for you, called vars().

所以上面的例子也可以做为:

So the above example can also be done as:

s = json.dumps(vars(foo)) # s set to: {"x":1, "y":2}

这篇关于将类实例序列化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆