简体   繁体   English

如何在 Python 中将 append 密钥项目键入到.json 文件?

[英]How to append key an item to .json file in Python?

How to append key an item to.json file in Python?如何在 Python 中将 append 密钥项目键入到.json 文件? (It is not necessary to have format {"Time": "Short"} ) I have.json: (不必有格式{"Time": "Short"} )我有.json:

{
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

I need to add one string "Time": "Short" to get:我需要添加一个字符串"Time": "Short"来获得:

  "random": [
    {
      "Volume": "Any",
      "Light": "Bright",
      "Time": "Short"
    }
  ]
}

What i did:我做了什么:

    data = json.load(json_file)
    data["req"].append({"Time": "Short"})
    json.dump(data, json_file, indent=3)

And.json looks like:和.json 看起来像:

{
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright",
      "Time": "Short"
    }
  ]
}

I think you may have copied and pasted then tweaked the key but this is essentially what you need:我认为您可能已经复制并粘贴然后调整了密钥,但这基本上是您需要的:

import json

dict_one = {
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

dict_one['random'][0].update(Time="Short")
print(json.dumps(dict_one))
# {"random": [{"Volume": "Any", "Light": "Bright", "Time": "Short"}]}

Your dictionary key "random" is a list of dictionaries, in your example only one.您的字典键“随机”是一个字典列表,在您的示例中只有一个。 So using dict_one['random'][0].update(Time="Short") we are updating the dictionary key 'random' and [0] relates to the first item in the list.因此,使用dict_one['random'][0].update(Time="Short")我们正在更新字典键 'random' 并且 [0] 与列表中的第一项相关。

If you need to update more items in the list then you'd have something like:如果您需要更新列表中的更多项目,那么您将拥有以下内容:

import json

dict_one = {
  "random": [
    {
      "Volume": "Any",
      "Light": "Bright"
    },
    {
      "Volume": "Any",
      "Light": "Bright"
    }
  ]
}

for item in dict_one['random']:
    item.update(Time="Short")

print(json.dumps(dict_one))
# {"random": [{"Volume": "Any", "Light": "Bright", "Time": "Short"}, {"Volume": "Any", "Light": "Bright", "Time": "Short"}]}

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

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