问题:如何使用Python动态构建JSON对象?

我是Python的新手,并且正在使用JSON数据。我想通过向现有JSON对象添加一些键值来动态构建JSON对象。

我尝试了以下方法,但得到了TypeError: 'str' object does not support item assignment

import json

json_data = json.dumps({})
json_data["key"] = "value"

print 'JSON: ', json_data

I am new to Python and I am playing with JSON data. I would like to dynamically build a JSON object by adding some key-value to an existing JSON object.

I tried the following but I get TypeError: 'str' object does not support item assignment:

import json

json_data = json.dumps({})
json_data["key"] = "value"

print 'JSON: ', json_data

回答 0

您在将对象编码为JSON字符串之前先对其进行构建:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

JSON是序列化格式,文本数据表示结构。它本身不是那个结构。

You build the object before encoding it to a JSON string:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.


回答 1

您可以创建Python字典并将其序列化为JSON,并且一行都不丑。

my_json_string = json.dumps({'key1': val1, 'key2': val2})

You can create the Python dictionary and serialize it to JSON in one line and it’s not even ugly.

my_json_string = json.dumps({'key1': val1, 'key2': val2})

回答 2

已经提供了一种解决方案,可以构建字典(或嵌套字典以获取更复杂的数据),但是如果您要构建对象,则可以尝试使用“ ObjDict”。这样可以更好地控制要创建的json,例如保留顺序,并允许将其构建为对象,这可能是概念的首选表示形式。

pip首先安装objdict。

from objdict import ObjDict

data = ObjDict()
data.key = 'value'
json_data = data.dumps()

There is already a solution provided which allows building a dictionary, (or nested dictionary for more complex data), but if you wish to build an object, then perhaps try ‘ObjDict’. This gives much more control over the json to be created, for example retaining order, and allows building as an object which may be a preferred representation of your concept.

pip install objdict first.

from objdict import ObjDict

data = ObjDict()
data.key = 'value'
json_data = data.dumps()

回答 3

您可以使用EasyDictdoc

EasyDict允许将字典值作为属性访问(递归工作​​)。python dict的类似于Javascript的属性点表示法。

使用方法

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

[ 安装 ]:

  • pip install easydict

You can use EasyDict library (doc):

EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.

USEAGE

>>> from easydict import EasyDict as edict
>>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}})
>>> d.foo
3
>>> d.bar.x
1

>>> d = edict(foo=3)
>>> d.foo
3

[INSTALLATION]:

  • pip install easydict

回答 4

以前的所有答案都是正确的,这是一种更简单的方法。例如,创建一个Dict数据结构来序列化和反序列化一个对象

请注意,Python中None是Null,我有意使用它来演示如何存储null并将其转换为json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

在此处输入图片说明

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I’m intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。