python替换json文件中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45435521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:01:55  来源:igfitidea点击:

python replace value in json file

pythonjson

提问by xergiopd

I have a json file named test.json and I need a python function for substitute some specific values in the same file. The json file is:

我有一个名为 test.json 的 json 文件,我需要一个 python 函数来替换同一文件中的某些特定值。json文件是:

[
  {
    "ParameterKey" : "HOME",
    "ParameterValue" : "/home"
  },
  {
    "ParameterKey" : "Shell",
    "ParameterValue" : "/bin/sh"
  },
  {
    "ParameterKey": "EnvHost",
    "ParameterValue": "localhost"
  },
  {
    "ParameterKey": "EnvUser",
    "ParameterValue": "stall"
  },
  {
    "ParameterKey": "Type",
    "ParameterValue": "super"
  }
]

I need to replace only "Shell" and "Type" to other values but I'm struggling to do so.

我只需要将“Shell”和“Type”替换为其他值,但我正在努力这样做。

回答by viveksyngh

You can do something like this.

你可以做这样的事情。

import json 
with open('/path/to/josn_file.json', 'r') as file:
     json_data = json.load(file)
     for item in json_data:
           if item['ParameterKey'] in ["Shell","Type"]:
              item['ParameterKey'] = "new value"
with open('/path/to/josn_file.json', 'w') as file:
    json.dump(json_data, file, indent=2)