Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and replace a part of a value in json file

I have a json file that I am using as a Dictionary in python. The json file is really long with 10k+ records. I need to replace the $home part in the "iscategorical" with the value of "id". After making the changes, I want to save this file so that I can use it again as a dictionary. Thank you for the help. Here is a sample:

{
"maps": [
    {
        "id": "xyzp",
        "iscategorical": "/u/$home/app/home"
    },
    {
        "id": "trtn",
        "iscategorical": "/u/app/$home/user"
    }
]}
like image 382
Mona Avatar asked Oct 31 '18 06:10

Mona


2 Answers

I am understanding that you are able to load the file successfully, and all you want to do is replace the strings and save the structure to file again.

For this, we can traverse the list of dictionaries in the data, and modify the value of item['iscategorical'] by replacing $home with the value of item['id'].

We can then dump the modified structure back to (a new) json file.

import json
with open('data.json') as f:
    data = json.load(f)

for item in data['maps']:
    item['iscategorical'] = item['iscategorical'].replace('$home', item['id'])

with open('new_data.json', 'w') as f:
    json.dump(data, f)
like image 111
sal Avatar answered Oct 08 '22 11:10

sal


Your question seems similar to - Parsing values from a JSON file? . However for your case below snippet should work.

import json

with open('idata.json') as infile:
  data = json.load(infile)

for elem in data["maps"]:
  elem['iscategorical']=elem['iscategorical'].replace('$home',elem['id'])

with open('odata.json', 'w') as outfile:
    json.dump(data, outfile)
like image 25
Jai Avatar answered Oct 08 '22 11:10

Jai