How To Write / Update A Json File In Python

We want to write to a JSON file, or maybe a file already has some JSON and we want to update it by adding more content to the file. We will use the Python JSON package to load the JSON file, after which we can write to the said file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
data = {
    "title": "Welcome to the home page",
     "description": "This is my application home page",
    "about": {
      "title": "About page",
      "content": "Here is about my application and it's functions.."
    },
    "legal": {
      "privacy":  {
      "title": "Privacy page",
      "content": "Some of the content we collect from you"
      } ,
      "terms": {
      "title": "Terms page",
      "content": "Follow our terms else be penalized"
      }
    }   
}
with open("written.json", "w") as jsonFile:
    json.dump(data, jsonFile, indent=4)

Now we have a file called written.json without JSON data. We want to update the file by adding some more data. "services": "We provide a range of services" To do this, we need to open the file(written.json), load the data into a Python dictionary then go ahead, update the file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
data_file = open("written.json", "r")
# json.loads returns a JSON file 
# as a Python Dictionary
data = json.load(data_file)
data_file.close()

data["services"] = "We provide a range of services"
# Update file
with open("written.json", "w") as jsonFile:
    json.dump(data, jsonFile, indent=4)

By default as you must have noticed, the file is updated by appending the new data to the end of the file. To update a specific key value, for example, the title key value, we can simply do:

1
2
3
4
5
6
7
8
9
data_file = open("written.json", "r")
# json.loads returns a JSON file 
# as a Python Dictionary
data = json.load(data_file)
data_file.close()
data["title"] = "I am the new title" # Welcome to the home page
# Write to file
with open("written.json", "w") as jsonFile:
    json.dump(data, jsonFile, indent=4)

Related Posts

0 Comments

12345

    00