Python Find and Replace String in JSON File Example
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Find and Replace Text in a File in Python?
- How to Set and Get Environment Variables in Python?
- Python Generate Random Number Between 0 to 1 Example
- Python Remove Character from List of Strings Example
- Python Generate List of Random Float Numbers Example
- How to Create List of Random Numbers in Python?
- How to Create a List of Numbers from 1 to N in Python?
- Python Convert List into String with Commas Example
- How to Remove null Values from the List in Python?
- Python Remove Empty String from List Example
- Python Delete Files with Specific Extension Example
- Python Post Request with pem File Example
- Python Post Request with Bearer Token Example
- How to Check if Today is Tuesday or not in Python?