Python JSON 添加键值对

Kar*_*hik 2 python arrays json python-2.7 python-3.x

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

JSON 文件:

{
  "students": [
    {
      "name": "Hendrick"
    },
    {
      "name": "Mikey"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

代码:

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)
Run Code Online (Sandbox Code Playgroud)

预期成绩:

{
  "students": [
    {
      "name": "Hendrick",
      "country": "UK"
    },
    {
      "name": "Mikey",
      "country": "UK"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 5

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

for s in json_decoded['students']:
    s['country'] = 'UK'
Run Code Online (Sandbox Code Playgroud)

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

with open("output.json", 'w') as json_file:
    json.dump(json_decoded, json_file)
Run Code Online (Sandbox Code Playgroud)