In this tutorial we will learn Python script to find and replace a string in a JSON file.
Python Script to Find and Replace a String in a JSON File
A JSON file can be loaded, its content modified, and then its revised data is saved back to the file using Python's built-in json package.
In the below example we will see how to look for and swap out a string in a JSON file:
import json # Use to load the JSON file with open('example.json', 'r') as f: data = json.load(f) # Use to find and replace the string old_str = 'old_string' new_str = 'new_string' for key in data.keys(): if isinstance(data[key], str): data[key] = data[key].replace(old_str, new_str) # Save the updated data back to the file with open('example.json', 'w') as f: json.dump(data, f)
In the above example, we first use json.load() to load the JSON file's content into a Python dictionary. Then, we iterate through the dictionary, checking each key's corresponding value to see if it is a string. If so, we use the replace() method to swap out the old string for the new one. Finally, we save the updated data back to the file using
Keep in mind that the
'w' mode used in the
open() function call overwrites the contents of the file. If you need to keep a backup of the original file then you can use a different filename or move it to a separate directory before running the script.