python - 如何将 Python dict 序列化为 JSON

标签 python json python-2.7 dictionary typeerror

<分区>

所以我有一些我想序列化为 JSON 的 python 字典

{'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject(someproperty=0, anotherproperty=0)}

但是 json.dumps 抛出一个 TypeError: SomeObject(someproperty=0, anotherproperty=0) is not JSON serializable

那么我怎样才能正确地序列化我的 python 字典呢?

最佳答案

问题是,python 不知道如何表示 SomeObject

您可以像这样创建后备:

import json

def dumper(obj):
    try:
        return obj.toJSON()
    except:
        return obj.__dict__

obj = {'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject(someproperty=0, anotherproperty=0)}

print json.dumps(obj, default=dumper, indent=2)

关于python - 如何将 Python dict 序列化为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36880065/

相关文章:

python - 如何显示pandas read_csv()函数读取的csv文件名?

python - 尝试使用 Python request.put 更新 Openhab 的 Rest API 中的值时出现错误 404

java - 解决递归关系中的 StackOverflow 异常

python - 是否有一种可接受的方法从不是 "from module import *"的全局命名空间中导入所有内容

google-app-engine - WTForms 不适用于 Google App Engine 1.6.1 和 Python 2.7

Python Pandas : remove entries based on the number of occurrences

python - 使用 boolean 向量提取 ndarray 的子数组

python - 在 Python 中删除小数点后的尾随零

python - 如何在 Flask 中实现需要登录的装饰器

python - 解析来自 COVID 曝光网站的 JSON 请求 - 无法打印所需结果