将Python对象转换为JSON输出

Turn Python object into JSON output

本问题已经有最佳答案,请猛点这里访问。

对于python来说,这是一个新的概念,它试图定义一个非常简单的类,该类包含一些值,然后将其输出到JSON符号中。

1
2
3
4
5
6
7
8
9
10
11
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)

我希望看到

1
2
3
4
5
{
 "double":"200",
 "triple":"300",
 "quadruple":"400"
}

但是得到一个错误:"typeerror:is not json serializable"


你可以mof the __dict__属性:连载P></

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

呼叫vars:You can alsoP></

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

使用:什么和为什么to使用字典是_ _ _ _承包或承包(VAR)呢?P></

为更多的复杂类的使用,考虑jsonpickleof the。P></

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.

重点地雷。P></