首页 > 解决方案 > Python JSON 添加键值对

问题描述

我正在尝试将键值对添加到现有的 JSON 文件中。我能够连接到父标签,如何为子项目增加价值?

JSON文件:

{
  "students": [
    {
      "name": "Hendrick"
    },
    {
      "name": "Mikey"
    }
  ]
}

代码:

import json

with open("input.json") as json_file:
    json_decoded = json.load(json_file)

json_decoded['country'] = 'UK'

with open("output.json", 'w') as json_file:
    for d in json_decoded[students]:
        json.dump(json_decoded, json_file)

预期成绩:

{
  "students": [
    {
      "name": "Hendrick",
      "country": "UK"
    },
    {
      "name": "Mikey",
      "country": "UK"
    }
  ]
}

标签: pythonarraysjsonpython-3.xpython-2.7

解决方案


您可以执行以下操作以dict按照您想要的方式进行操作:

for s in json_decoded['students']:
    s['country'] = 'UK'

json_decoded['students']是一个list字典,您可以简单地循环迭代和更新。现在您可以转储整个对象:

with open("output.json", 'w') as json_file:
    json.dump(json_decoded, json_file)

推荐阅读