【问题标题】:Adding values to JSON in Python2.7Python2.7 向 JSON 添加值
【发布时间】:2016-10-08 22:23:50
【问题描述】:

我的任务是将来自两个不同来源的数据组合成一个 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
        }]
    }]
]

我认为将其视为列表中的密钥对是可行的方法,但它似乎不起作用。谁能指出我正确的方向? 非常感谢!

【问题讨论】:

  • 看起来那是一个列表,可以在 python 中使用d[0][0]['breakdown'].append({"type": "type3", "count": 4533}) 附加到它

标签: python json python-2.7


【解决方案1】:

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

【讨论】:

    【解决方案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)
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      相关资源
      最近更新 更多