如何使可序列化的JSON类 [英] How to make a class JSON serializable

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

问题描述

如何使Python类可序列化?

How to make a Python class serializable?

一个简单的类:

class FileItem:
    def __init__(self, fname):
        self.fname = fname

我应该怎么做才能获得以下输出:

What should I do to be able to get output of:

>>> import json

>>> my_file = FileItem('/foo/bar')
>>> json.dumps(my_file)
TypeError: Object of type 'FileItem' is not JSON serializable

没有错误

推荐答案

您对预期的输出有想法吗?例如这样可以吗?

Do you have an idea about the expected output? For e.g. will this do?

>>> f  = FileItem("/foo/bar")
>>> magic(f)
'{"fname": "/foo/bar"}'

在这种情况下,您只能调用json.dumps(f.__dict__).

In that case you can merely call json.dumps(f.__dict__).

如果您想要更多的自定义输出,则必须子类化 ,并实现自己的自定义序列化.

If you want more customized output then you will have to subclass JSONEncoder and implement your own custom serialization.

有关一个简单的示例,请参见下文.

For a trivial example, see below.

>>> from json import JSONEncoder
>>> class MyEncoder(JSONEncoder):
        def default(self, o):
            return o.__dict__    

>>> MyEncoder().encode(f)
'{"fname": "/foo/bar"}'

然后将此类传递给 json.dumps() 方法为cls kwarg:

Then you pass this class into the json.dumps() method as cls kwarg:

json.dumps(cls=MyEncoder)

如果您还想解码,则必须向object_hook rel ="noreferrer"> JSONDecoder 类.例如

If you also want to decode then you'll have to supply a custom object_hook to the JSONDecoder class. For e.g.

>>> def from_json(json_object):
        if 'fname' in json_object:
            return FileItem(json_object['fname'])
>>> f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')
>>> f
<__main__.FileItem object at 0x9337fac>
>>> 

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

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