在Python2.7中向JSON添加值

2024-10-05 22:39:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是将两个不同来源的数据组合成一个JSON,供web服务使用。我决定用我发现很容易用的烧瓶。 无论如何,我正在检索这样的JSON(通过urlib2)。。。。你知道吗

[
    [{
        "timestamp": 1474088400000,
        "errors": 1018831,
        "errorTotal": 72400021,
        "errorTotal2": 0.013022892930509898,
        "business": 4814994,
        "breakdown": [{
            "type": "type1",
            "count": 603437
        }, {
            "type": "type2",
            "count": 256187
        }]
    }]
]

我所要做的就是在“breakdown”下添加一个新的密钥对,特别是“type3”,所以JSON对象如下所示。。。你知道吗

[
    [{
        "timestamp": 1474088400000,
        "errors": 1018831,
        "errorTotal": 72400021,
        "errorTotal2": 0.013022892930509898,
        "business": 4814994,
        "breakdown": [{
            "type": "type1",
            "count": 603437
        }, {
            "type": "type2",
            "count": 256187
        }, {
            "type": "type3",
            "count": 4533
        }]
    }]
]

我原以为把它当作一个列表中的密钥对来对待是个不错的办法,但它似乎不起作用。有人能给我指出正确的方向吗? 非常感谢!你知道吗


Tags: 数据jsontypecount来源密钥businesstimestamp
2条回答
  1. 加载json字符串

    json_data = json.loads(json_string)
    
  2. 迭代对象并append"breakdown"

    for item in json_data:
        for json_dict in item:
            json_dict["breakdown"].append({"type": "type3", "count": 4533})
    
  3. 将其转换回JSON字符串

    json_string = json.dumps(json_data)
    

首先,应该将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)

相关问题 更多 >