简体   繁体   English

Python JSON添加键值对

[英]Python JSON add Key-Value pair

I'm trying to add key value pairs into the existing JSON file. 我正在尝试将键值对添加到现有的JSON文件中。 I am able to concatenate to the parent label, How to add value to the child items? 我可以连接到父标签,如何为子项目增加价值?

JSON file: JSON文件:

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

Code: 码:

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)

Expected Results: 预期成绩:

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

You can do the following in order to manipulate the dict the way you want: 您可以执行以下操作以按所需方式操作dict

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

json_decoded['students'] is a list of dictionaries that you can simply iterate and update in a loop. json_decoded['students']是字典的list ,您可以简单地循环访问和更新。 Now you can dump the entire object: 现在您可以转储整个对象:

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

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

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

    with open("output.json", 'w') as json_out_file:
        json.dump(json_decoded, json_out_file)
  1. opened a json file ie input.json 打开一个json文件,即input.json
  2. iterated through each of its element 遍历每个元素
  3. add a key named "country" and dynamic value "UK", to each element 向每个元素添加名为“国家”的键和动态值“ UK”
  4. opened a new json file with the modified JSON. 用修改后的JSON打开了一个新的json文件。

Edit: 编辑:

Moved writing to output file inside to first with segment. 将写入到输出文件的写入移到了with段的第一个。 Issue with earlier implemenation is that json_decoded will not be instantiated if opening of input.json fails. 较早实现的问题是,如果打开input.json失败,则不会实例化json_decoded And hence, writing to output will raise an exception - NameError: name 'json_decoded' is not defined 因此,写入输出将引发异常NameError: name 'json_decoded' is not defined

This gives [None, None] but update the dict: 这给出了[None, None]但更新了dict:

a = {'students': [{'name': 'Hendrick'}, {'name': 'Mikey'}]}
[i.update({'country':'UK'}) for i in a['students']]
print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM