Python 新手,尝试定义一个非常简单的类,它将保存一些值,然后将其输出为 JSON 表示法。
import json
class Multiple:
def __init__(self, basis):
self.double = basis * 2
self.triple = basis * 3
self.quadruple = basis * 4
m = Multiple(100)
json.dumps(m)
我希望看到类似的东西
{
"double":"200",
"triple":"300",
"quadruple":"400"
}
而是得到一个错误:“TypeError: <main.Multiple object at 0x0149A3F0> is not JSON serializable”
你可以序列化 m
的 __dict__
属性:
In [214]: json.dumps(m.__dict__)
Out[214]: '{"quadruple": 400, "double": 200, "triple": 300}'
你 can也可以调用 vars
:
In [216]: json.dumps(vars(m))
Out[216]: '{"quadruple": 400, "double": 200, "triple": 300}'
使用什么以及为什么:
Use `__dict__` or `vars()`?
对于更复杂的类,考虑使用 jsonpickle
.
jsonpickle
is a Python library for serialization and deserialization
of complex Python objects to and from JSON. The standard Python
libraries for encoding Python into JSON, such as the stdlib’s json
,
simplejson
, and demjson
, can only handle Python primitives that have a
direct JSON equivalent (e.g. dict
s, list
s, str
ings, int
s, etc.).
jsonpickle
builds on top of these libraries and allows more complex
data structures to be serialized to JSON.
强调我的。