замена строки в json in python

To replace a specific string in a JSON file in Python, you first need to load the JSON data, replace the string, and then save the updated JSON data. Here's an example:

main.py
import json

# Open the JSON file
with open('example.json') as json_file:
    data = json.load(json_file)

# Replace the string in the JSON data
old_string = 'old value'
new_string = 'new value'
updated_data = json.dumps(data).replace(old_string, new_string)

# Save the updated JSON data back to the file
with open('example.json', 'w') as json_file:
    json_file.write(updated_data)
385 chars
15 lines

Make sure to replace 'example.json' with the actual path to your JSON file. This code will replace all occurrences of the old string with the new string in the JSON data and save the updated data back to the file.

Note: If the JSON file is quite large, consider using a streaming JSON processor like ijson to avoid loading the entire JSON data into memory at once.

gistlibby LogSnag