将Python对象转换为JSON输出 [英] Turn Python object into JSON output
问题描述
Python的新手,试图定义一个非常简单的类,该类将包含一些值,然后将其输出为JSON表示法.
New to Python, trying to define a very simple class that will hold a few values, and then get it output into JSON notation.
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:< 主要.位于0x0149A3F0>的多个对象不是JSON可序列化的"
but instead get an error: "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}'
您可以也调用
You can also call vars
:
In [216]: json.dumps(vars(m))
Out[216]: '{"quadruple": 400, "double": 200, "triple": 300}'
使用什么以及为什么: 使用`__dict__`或`vars()`?
What to use and why: Use `__dict__` or `vars()`?
对于更复杂的类,请考虑使用 jsonpickle
.
For more complicated classes, consider the use of jsonpickle
.
jsonpickle
是用于序列化和反序列化的Python库 复杂的Python对象与JSON之间的交互.标准的Python 用于将Python编码为JSON的库,例如stdlib的json
,simplejson
和demjson
,只能处理具有 等效的直接JSON(例如dict
s,list
s,str
ings,int
s等).jsonpickle
建立在这些库的顶部,并允许更复杂 数据结构要序列化为JSON.
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’sjson
,simplejson
, anddemjson
, 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.
强调我的.
这篇关于将Python对象转换为JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!