Python (Scripting) - Update a JSON file

by
Jeremy Canfield |
Updated: November 06 2023
| Python (Scripting) articles
Here is a very simple example of how you can update a JSON file. At a high level.
- Store the original JSON file in a dictionary using json.load
- Update the dictonary
- Overwrite the original JSON file with the updated dictonary using file open and jump_dumps.
For example, let's say /tmp/events.json ontains the following.
{
"events" : [
{
"foo":"Hello"
},
{
"bar":"World"
}
]
}
In this example, the "foo" key will be updated from "Hello" to "Goodbye".
#!/usr/bin/python3
import json
file = open("/tmp/events.json")
try:
parsed_json = json.load(file)
except Exception as exception:
print(f"Got the following exception json.load: {exception}")
sys.exit(1)
file.close()
for event in parsed_json['events']:
if event['title'] == "Hello:
event['title'] = "Goodbye"
try:
json_object = json.dumps(parsed_json, indent=4)
except Exception as exception:
print(f"Got the following exception when attempting json.dumps: {exception}")
sys.exit(1)
try:
with open("/tmp/events.json", "w") as file:
file.write(json_object)
file.write("\n")
except Exception as exception:
print(f"Got the following exception when attempting file open write: {exception}")
sys.exit(1)
print(f"Successfully updated the 'foo' key in {file} from 'Hello' to 'Goodbye'")
Did you find this article helpful?
If so, consider buying me a coffee over at