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"
}
]}
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With