ItSolutionStuff.com

Python Find and Replace String in JSON File Example

By Hardik Savani • October 30, 2023
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: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Find and Replace Text in a File in Python?

Read Now →

How to Set and Get Environment Variables in Python?

Read Now →

Python Generate Random Number Between 0 to 1 Example

Read Now →

Python Remove Character from List of Strings Example

Read Now →

Python Generate List of Random Float Numbers Example

Read Now →

How to Create List of Random Numbers in Python?

Read Now →

How to Create a List of Numbers from 1 to N in Python?

Read Now →

Python Convert List into String with Commas Example

Read Now →

How to Remove null Values from the List in Python?

Read Now →

Python Remove Empty String from List Example

Read Now →

Python Delete Files with Specific Extension Example

Read Now →

Python Post Request with pem File Example

Read Now →

Python Post Request with Bearer Token Example

Read Now →

How to Check if Today is Tuesday or not in Python?

Read Now →