在Python2.7中向JSON添加值
我的任务是将来自两个不同来源的数据组合成一个JSON,供web服务使用。我决定用我发现很容易使用的烧瓶。 无论如何,我正在检索类似这样的JSON(通过urlib2) 我所要做的就是在“细分”下添加一个新的密钥对,特别是“type3”,所以JSON对象如下所示在Python2.7中向JSON添加值,python,json,python-2.7,Python,Json,Python 2.7,我的任务是将来自两个不同来源的数据组合成一个JSON,供web服务使用。我决定用我发现很容易使用的烧瓶。 无论如何,我正在检索类似这样的JSON(通过urlib2) 我所要做的就是在“细分”下添加一个新的密钥对,特别是“type3”,所以JSON对象如下所示 [ [{ "timestamp": 1474088400000, "errors": 1018831, "errorTotal": 72400021, "errorTo
[
[{
"timestamp": 1474088400000,
"errors": 1018831,
"errorTotal": 72400021,
"errorTotal2": 0.013022892930509898,
"business": 4814994,
"breakdown": [{
"type": "type1",
"count": 603437
}, {
"type": "type2",
"count": 256187
}, {
"type": "type3",
"count": 4533
}]
}]
]
我原以为把它当作列表中的键对来对待是一个不错的办法,但它似乎不起作用。谁能给我指出正确的方向吗?
非常感谢 首先,您应该将json读入Python对象:
data = json.loads(jsonstring)
然后转到要修改的对象。数据看起来像[[[{…'breakdown':…}]
,因此它是一个字典列表。我想你想要所有这些:
for d in data:
for dd in d:
d['breakdown'].append({"type": "type3", "count": 4533})
然后将其转换回json:
update_json = json.dumps(data)
json
字符串
json_data = json.loads(json_string)
json_string = json.dumps(json_data)
附加到“细分”
键
for item in json_data:
for json_dict in item:
json_dict["breakdown"].append({"type": "type3", "count": 4533})
JSON
字符串
json_data = json.loads(json_string)
json_string = json.dumps(json_data)
看起来这是一个列表,可以在python中用
d[0][0]['breakdown']追加到它。追加({“type”:“type3”,“count”:4533})