python - 将 Python 对象转换为 JSON 输出

标签 python json

<分区>

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

强调我的。

关于python - 将 Python 对象转换为 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45834577/

相关文章:

Python 到 Mat 文件 : export list of string to ordinar matrix of chars (not a cell-array! )

python - 如何在python中一次性找到链表的中间元素?

javascript - JSON.stringify 中的注释字段被忽略

javascript - php返回带有angularjs错误的json

java - 如何用多个外部jar编译一个java源文件?

python - 在没有 numpy 的情况下制作多维数组的好方法

python - 我想同时运行 2 个 for 循环,可以吗?

python - 从 Google Drive Python API 获取 createdDate 以供下载

JSON 模式 if/then 需要嵌套对象

java - 如何防止 Map 中的空值和 bean 中的空字段通过 Jackson 序列化