Python – Append to JSON File

Learn to read a JSON file and append JSON data into a file in Python. 1. Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Refer to the following articles to learn how to read JSON from a …

Python

Learn to read a JSON file and append JSON data into a file in Python.

1. Steps for Appending to a JSON File

In Python, appending JSON to a file consists of the following steps:

  • Read the JSON in Python dict or list object.
  • Append the JSON to dict (or list) object by modifying it.
  • Write the updated dict (or list) object into the original file.

Refer to the following articles to learn how to read JSON from a file and write JSON to a file in Python.

2. Appending to a JSON Array using Python List

The users.json file has a list of 2 users. We will append a third user to it.

[ { "Name": "Person_1", "Age": 11, "Email": "11@gmail.com" }, { "Name": "Person_2", "Age": 22, "Email": "22@gmail.com" } ]
import json from os import path filename = 'c:/temp/users.json' listObj = [] # Check if file exists if path.isfile(filename) is False: raise Exception("File not found") # Read JSON file with open(filename) as fp: listObj = json.load(fp) # Verify existing list print(listObj) print(type(listObj)) listObj.append({ "Name": "Person_3", "Age": 33, "Email": "33@gmail.com" }) # Verify updated list print(listObj) with open(filename, 'w') as json_file: json.dump(listObj, json_file, indent=4, separators=(',',': ')) print('Successfully appended to the JSON file') 

The updated JSON file is:

[ { "Name": "Person_1", "Age": 11, "Email": "11@gmail.com" }, { "Name": "Person_2", "Age": 22, "Email": "22@gmail.com" }, { "Name": "Person_3", "Age": 33, "Email": "33@gmail.com" } ]

3. Appending to a JSON Object using Python Dictionary

The users.json file has a list of 2 users. We will append a new attribute role and modify an existing attribute Age.

{	"Name": "Person_1",	"Age": 11,	"Email": "11@gmail.com" }
import json from os import path filename = 'c:/temp/users.json' dictObj = [] # Check if file exists if path.isfile(filename) is False: raise Exception("File not found") # Read JSON file with open(filename) as fp: dictObj = json.load(fp) # Verify existing dict print(dictObj) print(type(dictObj)) dictObj.update({"Age": 12,"Role": "Developer"}) # Verify updated dict print(dictObj) with open(filename, 'w') as json_file: json.dump(dictObj, json_file, indent=4, separators=(',',': ')) print('Successfully written to the JSON file') 

The updated JSON file is:

{ "Name": "Person_1", "Age": 12, "Email": "11@gmail.com", "Role": "Developer" } 

4. AttributeError: ‘dict’ object has no attribute ‘append’

We may get this error if the JSON object read from the json.load() method is of type dict.

The first example reads a JSON list [...] so the loaded object is of type list. If we are reading a file that has JSON object {...} then the loaded object will be of type dictionary and the above code will give AttributeError while invoking the list operations.

{'Name': 'Person_1', 'Age': 11, 'Email': '11@gmail.com'} <class 'dict'> Traceback (most recent call last): File "C:\temp\temp.py", line 20, in <module> listObj.append({ AttributeError: 'dict' object has no attribute 'append'

To fix this error, be mindful of what JSON structure you are reading from the JSON file.

  • Read JSON object to Python dict object.
  • Read JSON array to Python list object.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.