繁体   English   中英

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

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

如何在 Python 中将 append 密钥项目键入到.json 文件? (不必有格式{"Time": "Short"} )我有.json:

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

我需要添加一个字符串"Time": "Short"来获得:

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

我做了什么:

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

和.json 看起来像:

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

我认为您可能已经复制并粘贴然后调整了密钥,但这基本上是您需要的:

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"}]}

您的字典键“随机”是一个字典列表,在您的示例中只有一个。 因此,使用dict_one['random'][0].update(Time="Short")我们正在更新字典键 'random' 并且 [0] 与列表中的第一项相关。

如果您需要更新列表中的更多项目,那么您将拥有以下内容:

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