如何将Python dict序列化为JSON

joh*_*ies 3 python json dictionary typeerror python-2.7

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

{'someproperty': 0, 'anotherproperty': 'value', 'propertyobject': SomeObject(someproperty=0, anotherproperty=0)}
Run Code Online (Sandbox Code Playgroud)

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

那么如何正确序列化我的python dict呢?

Mat*_*dus 6

问题是,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)
Run Code Online (Sandbox Code Playgroud)


meg*_*gha 5

Python 只能序列化内置数据类型的对象。 在您的情况下,“SomeObject”是Python无法序列化的用户定义类型。如果您尝试序列化任何不可 json 可序列化的数据类型,则会收到 TypeError“ TypeError: is not JSON Serialabilable ”。因此应该有一个中间步骤将这些非内置数据类型转换为Python内置的可序列化数据结构(列表、字典、数字和字符串)。

因此,让我们将您的 SomeObject 转换为 python 字典,因为字典是表示您的对象的最简单方法(因为它具有键/值对)。您只需将所有 SomeObject 实例属性复制到新字典即可! myDict = self.__dict__.copy() 这个myDict现在可以是你的“propertyobject”的值。

此步骤之后是将字典转换为字符串(JSON 格式,但可以是 YAML、XML、CSV...) - 对我们来说它将是jsonObj = JSON.dumps(finalDict)

最后一步是将 jsonObj 字符串写入磁盘上的文件!