Python Find and Replace String in JSON File Example

By Hardik Savani October 30, 2023 Category : Python

Hi Dev,

In this quick guide, we will teach you python find and replace string in json file. step by step explain replace value in json file python. This article will give you a simple example of how to replace value in json file using python. This tutorial will give you a simple example of python search and replace in json file.

Here, i will give you a very simple example to search and replace string in file using python script. we will use open() and replace() function to find string and replace in file using python 3. so, let's see the simple example:

Example:

Here, we will create an "sample.json" file as like below:

sample.json

{
    "id": 1, 
    "name": "Hardik Savani", 
    "email": "hardik@gmail.com", 
    "city": "Rajkot",
    "website": "example.com"
},
{
    "id": 2, 
    "name": "Paresh Savani", 
    "email": "paresh@gmail.com", 
    "city": "Rajkot",
    "website": "example.com"
}

Now, we will create main.py file and find string from that file as like the below code:

main.py

findString = "example.com"
replaceString = "itsolutionstuff.com"
  
with open('sample.json', 'r') as f:
    data = f.read()
    data = data.replace(findString, replaceString)
  
with open('sample.json', 'w') as f:
    f.write(data)
    
print("JSON Data replaced")

Output:

sample.json

{
    "id": 1, 
    "name": "Hardik Savani", 
    "email": "hardik@gmail.com", 
    "city": "Rajkot",
    "website": "itsolutionstuff.com"
},
{
    "id": 2, 
    "name": "Paresh Savani", 
    "email": "paresh@gmail.com", 
    "city": "Rajkot",
    "website": "itsolutionstuff.com"
}

I hope it can help you...

Tags :
Shares