简体   繁体   English

如何将Python dict序列化为JSON

[英]How to serialize Python dict to JSON

So I have some python dict that I want to serialize to JSON 所以我有一些想要将序列化为JSON的python字典

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

but json.dumps throws a TypeError: SomeObject(someproperty=0, anotherproperty=0) is not JSON serializable 但是json.dumps引发TypeError: SomeObject(someproperty=0, anotherproperty=0) is not JSON serializable

So how can I serialize my python dict properly? 那么如何正确序列化我的python dict呢?

The problem is, python doesn't know how to represent SomeObject 问题是,python不知道如何表示SomeObject

You can create a fallback like so: 您可以像这样创建后备广告:

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 can serialize only the objects that is a built in data type. Python只能序列化内置数据类型的对象。 In your case, "SomeObject" is a User defined type that Python cannot serialize. 在您的情况下,“ SomeObject”是Python无法序列化的用户定义类型。 If you try to serialize any data type which is not json serializable, you get a TypeError " TypeError: is not JSON serializable ". 如果您尝试序列化无法json可序列化的任何数据类型,则会收到TypeError“ TypeError:is not JSON serializable ”。 So there should be an intermediate step that converts these non built in data types into Python built in serializable data structure (list, dict, number and string). 因此,应该有一个中间步骤将这些非内置数据类型转换为内置于可序列化数据结构(列表,字典,数字和字符串)的Python。

So let us convert your SomeObject into a python dictionary, since dictionary is the easiest way to represent your Object(as it has key/value pairs). 因此,让我们将SomeObject转换为python字典,因为字典是表示对象的最简单方法(因为它具有键/值对)。 You could just copy all your SomeObject instance attributes to a new dictionary and you are set! 您只需将所有SomeObject实例属性复制到新词典中,就可以设置好了! myDict = self.__dict__.copy() This myDict can now be the value of your "propertyobject". myDict = self .__ dict __。copy()现在,该myDict可以是“属性对象”的值。

After this step is when you convert dictionary to a string (JSON format, but it can be YAML, XML, CSV...) - for us it will be jsonObj = JSON.dumps(finalDict) 在此步骤之后,当您将字典转换为字符串(JSON格式,但可以是YAML,XML,CSV ...)时-对我们而言,它将是jsonObj = JSON.dumps(finalDict)

Last step is to write jsonObj string to a file on disk! 最后一步是将jsonObj字符串写入磁盘上的文件!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM