Append to JSON file in Python
In this article, we are going to show you how to append to JSON file in Python. Python has a built-in package called json which lets us working with JSON. There are several ways to do it. But we use a simple way for your easy understanding.
First, you have to know about JSON.
- The expansion of JSON is JavaScript Object Notation.
- Used for data transmission that takes place between a server and a web application.
- It is a collection of key and value pairs.
Python program to append JSON file
Let’s have a look at the following example.
js1.json:
{"Name": "ram", "Age": "20", "Gender": "male"}
import json dict1= {"City": "chennai"} with open("js1.json", "r+") as fi: data = json.load(fi) data.update(dict1) fi.seek(0) json.dump(data, fi)
In this example, we have imported a json module. The functions used in this program are as follows.
1.loads(): purpose of loads() is to parse the JSON string. It takes JSON string as a parameter and returns the python dictionary object.
- Syntax: json.loads(json_string)
2.update(): this function updates the dictionary with elements from another dictionary object which is a key-value pair. It takes another dictionary as an argument and returns none.
- Syntax: dict.update(other_dict)
3.dumps(): this function converts Python object to JSON string. It takes a Python object as an argument and returns the JSON string.
- Syntax: json.dumps(object)
4.seek(): this function changes the position of a filehandle to a given position. It takes offset(no.of positions to be moved) and from(point of reference) as parameters. When we set the offset value to 0, it points to the beginning of a file.
- Syntax: file.seek(offset,from)
After executing the above program, the JSON file will be modified as follows.
js1.json:
{"Name": "ram", "Age": "20", "Gender": "male", "City": "chennai"}
I hope that you have learned something useful from this tutorial.
When I try the above I get an error!!!
Exception has occurred: AttributeError
‘list’ object has no attribute ‘update’
File “/home/delacy/Documents/PyProgs/json/try.py”, line 11, in
data.update(a_dictionary)
If I change data,update to data.append it works but adds to the end of the list, if run again it adds another list to the end of the last list????
I want it to over write!!
What can i do to add for example another gender or another city, so it becames like:
{“Name”: “ram”, “Age”: “20”, “Gender”: “male”,”female”, “City”: “chennai”,”barcelona”}
Jsons have either lists or maps as fields, so “City” needs to have a list as its value, [“chennai”,”barcelona”]