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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23110383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:15:16  来源:igfitidea点击:

How to dynamically build a JSON object with Python?

pythonjson

提问by Backo

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.

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

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

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

import json

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

print 'JSON: ', json_data

采纳答案by Martijn Pieters

You build the object beforeencoding it to a JSON string:

在将对象编码为 JSON 字符串之前构建对象:

import json

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

JSON is a serializationformat, textual data representinga structure. It is not, itself, that structure.

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

回答by innov8

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.

已经提供了一个允许构建字典(或用于更复杂数据的嵌套字典)的解决方案,但是如果您希望构建一个对象,那么也许可以尝试“ObjDict”。这提供了对要创建的 json 的更多控制,例如保留顺序,并允许构建为对象,这可能是您的概念的首选表示。

pip install objdict first.

首先pip安装objdict。

from objdict import ObjDict

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

回答by sscarduzio

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

您可以在一行中创建 Python 字典并将其序列化为 JSON,它甚至不难看。

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

回答by Benyamin Jafari

You could use EasyDictlibrary (doc):

您可以使用EasyDict文档

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

EasyDict 允许访问 dict 值作为属性(递归工作​​)。python dicts的类似于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


[Installation]:

安装】:

  • pip install easydict
  • pip install easydict

回答by grepit

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

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

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

注意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)

enter image description here

在此处输入图片说明