如何使类 JSON 可序列化

编程入门 行业动态 更新时间:2024-10-10 03:32:10
本文介绍了如何使类 JSON 可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何使 Python 类可序列化?

一个简单的类:

类文件项:def __init__(self, fname):self.fname = fname

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

>>>导入json>>>my_file = FileItem('/foo/bar')>>>json.dumps(my_file)类型错误:FileItem"类型的对象不是 JSON 可序列化的

没有错误

解决方案

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

>>>f = FileItem("/foo/bar")>>>魔法(女)'{"fname": "/foo/bar"}'

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

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

一个简单的例子,见下文.

>>>从 json 导入 JSONEncoder>>>类 MyEncoder(JSONEncoder):定义默认(自我,o):返回 o.__dict__>>>MyEncoder().encode(f)'{"fname": "/foo/bar"}'

然后你将这个类传递到 json.dumps() 方法为 cls kwarg:

json.dumps(cls=MyEncoder)

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

>>>def from_json(json_object):如果 json_object 中的fname":返回文件项(json_object['fname'])>>>f = JSONDecoder(object_hook = from_json).decode('{"fname": "/foo/bar"}')>>>F<__main__.FileItem 对象在 0x9337fac>>>>

How to make a Python class serializable?

A simple class:

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

Without the error

解决方案

Do you have an idea about the expected output? For example, will this do?

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

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"}'

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

json.dumps(cls=MyEncoder)

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

>>> 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 可序列化

本文发布于:2023-11-11 08:48:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577934.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!