如何动态构建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
601141 次浏览

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

import json


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

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

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

先安装PIP对象。

from objdict import ObjDict


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

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

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

你可以使用EasyDict(doc):

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

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

(请注意 None在python中是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

  • json.loads接受字符串作为输入,并返回一个字典作为输出。
  • json.dumps接受字典作为输入,并返回一个字符串作为输出。

如果你需要将JSON数据转换为python对象,它可以在一行中使用Python3来完成,而不需要额外安装,使用SimpleNamespaceobject_hook:

从字符串

import json
from types import SimpleNamespace


string = '{"foo":3, "bar":{"x":1, "y":2}}'


# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))


print(x.foo)
print(x.bar.x)
print(x.bar.y)

输出:

3
1
2

从文件:

JSON对象:data.json

{
"foo": 3,
"bar": {
"x": 1,
"y": 2
}
}
import json
from types import SimpleNamespace


with open("data.json") as fh:
string = fh.read()


# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))


print(x.foo)
print(x.bar.x)
print(x.bar.y)

输出:

3
1
2

从请求

import json
from types import SimpleNamespace
import requests


r = requests.get('https://api.github.com/users/MilovanTomasevic')


# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))


print(x.name)
print(x.company)
print(x.blog)

输出:

Milovan Tomašević
NLB
milovantomasevic.com

为了更漂亮、更快地从API访问JSON响应,请查看这种反应

我创建了一个递归函数来遍历表示json结构的套字典。

  myjson={}
myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
myjson["Creative"]= {
"1067405": {
"id": "1067405",
"url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
},
"1067406": {
"id": "1067406",
"url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
},
"1067407": {
"id": "1067407",
"url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
}
}
myjson["Offer"]= {
"advanced_targeting_enabled": "f",
"category_name": "E-commerce/ Shopping",
"click_lifespan": "168",
"conversion_cap": "50",
"currency": "USD",
"default_payout": "1.5"
}


json_data = json.dumps(myjson)


#reverse back into a json


paths=[]
def walk_the_tree(inputDict,suffix=None):
for key, value in inputDict.items():
if isinstance(value, dict):
if suffix==None:
suffix=key
else:
suffix+=":"+key


walk_the_tree(value,suffix)
else:
paths.append(suffix+":"+key+":"+value)
walk_the_tree(myjson)
print(paths)


#split and build your nested dictionary
json_specs = {}
for path in paths:
parts=path.split(':')
value=(parts[-1])
d=json_specs
for p in parts[:-1]:
if p==parts[-2]:
d = d.setdefault(p,value)
else:
d = d.setdefault(p,{})
    

print(json_specs)


Paths:
['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']

你可以使用jsonCreater模块创建json文件

        `jsonCreator.createJson(dict,”fileName”,[“path”])`