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

查看:119
本文介绍了将类实例序列化为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)

失败,并告诉我testclass不可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'\x80\x03c__main__\ntestclass\nq\x00)\x81q\x01}q\x02b.'

我在做什么错了?

推荐答案

基本问题是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()函数,并使该函数为您的类发出正确的JSON.

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:

   

    Serializing arbitrary Python objects to JSON using __dict__

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

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