Bootstrap FreeKB - Python (Scripting) - Update a JSON file
Python (Scripting) - Update a JSON file

Updated:   |  Python (Scripting) articles

Here is a very simple example of how you can update a JSON file. At a high level.

  1. Store the original JSON file in a dictionary using json.load
  2. Update the dictonary
  3. 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 Buy Me A Coffee



Comments


Add a Comment


Please enter cd916a in the box below so that we can be sure you are a human.