Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace value in json file [closed]

Tags:

python

json

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:

[
  {
    "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.

like image 602
xergiopd Avatar asked Aug 01 '17 10:08

xergiopd


1 Answers

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)
like image 67
viveksyngh Avatar answered Sep 22 '22 11:09

viveksyngh