close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to find and replace a part of a value in json file in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

    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.

  2. find and replace a part of a value in json file

    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.

Method 1

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)

Method 2


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)

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read