Python program to read and write JSON from a file

How to read and write data from a JSON file in python

JavaScript Object Notation or JSON is one of the most commonly used data interchanging format. It is a language independent format and can be used in any language in the same way.

Python provides one built in package called json to work with JSON data. JSON data is mostly consists of key-value pairs like python dictionary. Using json module, we can easily convert JSON data to a dictionary and a dictionary to JSON.

Writing JSON to a file and reading JSON data from a file can be done easily with json module.

Writing JSON data to a file:

JSON is like a dictionary in python. TO write JSON value to a file, we can write one dictionary to a file. Python json module provides two methods: dump and dumps. Both methods can be used to convert one dictionary to JSON.

The conversion to and from JSON to python dictionary uses the below table:

JSON Python
object dict
string str
array list
int int
real float
true True
false False
null None

Write JSON data to a file using json.dump() :

json.dump() method takes two parameters. The first one is the python dictionary that we need to convert to a JSON and the second one is the file pointer, where we are dumping the data.

It looks as like below:

json.dump(dictionary, file)

Let’s take a look at the below example program:

import json
student_dictionary = {
    "name": "Chandler",
            "age": 12,
            "updated": True,
            "notes": None,
            "marks": 90.0
}

with open("output.json", "w") as out:
    json.dump(student_dictionary, out)

Here, we are writing the dictionary student_dictionary to a file output.json in the same folder where this python file exists. It will create that json file if it doesn’t exist. If you open that file, it will hold the contents of this dictionary in JSON format :

python json write to file

None is converted to null and True is converted to true as we have seen in the above conversion table.

Write JSON data to file using json.dumps():

json.dumps() actually converts one JSON dictionary to a JSON object. We can write that object to a file.

It is defined as below:

json.dumps(dict, indent)

indent is used for indentation. It is useful if you want to pretty print JSON data to a file. Let’s change the above example to use json.dumps() :

import json
student_dictionary = {
    "name": "Chandler",
            "age": 12,
            "updated": True,
            "notes": None,
            "marks": 90.0
}

student_json = json.dumps(student_dictionary)

with open("output.json", "w") as out:
    out.write(student_json)

It will write the dictionary to the file as shown in the above example. But, if I use indent :

import json
student_dictionary = {
    "name": "Chandler",
            "age": 12,
            "updated": True,
            "notes": None,
            "marks": 90.0
}

student_json = json.dumps(student_dictionary, indent=4)

with open("output.json", "w") as out:
    out.write(student_json)

The data will be formatted in the file: python json pretty print

This is actually useful if you are dealing with a large JSON object.

Reading JSON data from a file:

Reading JSON data means deserialize it to a python dictionary object. You can get the JSON data from any other platform or program and convert it to a python object using this method. json.load() method is used to load JSON from a file to a python object. It takes only file pointer as the parameter. Once we get the python object, we can access its values.

import json

with open("output.json", "r") as input_file:
    json_dict = json.load(input_file)

print(json_dict)
print(json_dict["name"])
print(json_dict["age"])

If you run this program, it will print the below output:

{'name': 'Chandler', 'age': 12, 'updated': True, 'notes': None, 'marks': 90.0}
Chandler
12

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊