将Python对象转换为JSON输出

2024-06-30 15:59:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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。0x0149A3F0处的多个对象不是JSON可序列化的”


Tags: importselfjson定义initdefbasismultiple
1条回答
网友
1楼 · 发布于 2024-06-30 15:59:54

可以序列化m__dict__属性:

In [214]: json.dumps(m.__dict__)
Out[214]: '{"quadruple": 400, "double": 200, "triple": 300}'

can还可以调用^{}

In [216]: json.dumps(vars(m))
Out[216]: '{"quadruple": 400, "double": 200, "triple": 300}'

使用内容和原因: Use `__dict__` or `vars()`?


对于更复杂的类,请考虑使用^{}

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. dicts, lists, strings, ints, etc.). jsonpickle builds on top of these libraries and allows more complex data structures to be serialized to JSON.

强调我的。

相关问题 更多 >