How to Find and Replace String in JSON Filein Python?

02-Jun-2023

.

Admin

How to Find and Replace String in JSON Filein Python?

Hi Dev,

This tutorial is focused on how to find and replace strings in JSON files in Python. I explained simply about Python finding and replacing strings in JSON files. you will learn to replace values in JSON file Python. We will use how to replace values in JSON files using Python. Here, Create a basic example of Python search and replace it in a JSON file.

Here, I will give you a very simple example to search and replace a string in a file using Python script. we will use the open() and replace() function to find string and replace them in a 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": "Piyush Savani",

"email": "piyush@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 = "nicesnippets.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:

{

"id": 1,

"name": "Hardik Savani",

"email": "hardik@gmail.com",

"city": "Rajkot",

"website": "nicesnippets.com"

},

{

"id": 2,

"name": "Piyush Savani",

"email": "piyush@gmail.com",

"city": "Rajkot",

"website": "nicesnippets.com"

}

#Python