How to save structured data with JSON in python?



Introduction-JSON in python

A JSON (JavaScript Object Notation) format was originally developed for JavaScript. However, it has become a common format used by many languages, including Python and it is already familiar with many programmers.

The use of the JSON module is a good choice for data interoperability. A JSON in python allows you to dump simple data structures into a file and load the data from that file when you run the program next time. It is a useful and portable format. We can share data stored in the JSON format with people who work in many other programming languages.

If you do not use a JSON module to store data, everything that is stored through user input in a variable will be lost as soon as the interpreter is closed. So, we always want to save the information entered. A simple way to do this involves storing your data using the JSON module.



JSON methods

JSON module has two methods;

  1. json.dump()
  2. json.load()
1. json.dump()

The method is used to dump a simple python data structure into a file object. It takes two arguments; a piece of data to store and a file object which will be used to store the data.

Example:

# seasondump.py

import json
file = 'season.json'
with open(file, 'w') as f:
    season = input("Enter the four seasons: ")
    json.dump(season, f)

When this program is executed, it will ask you to enter four seasons which will be stored inside the season.json file, as shown below:

Enter the four seasons: Summer, Winter, Spring, Autumn


2. json.load()

The method is used to load data from the file when we run the program next time.

Example:

#seasonload.py

import json
with open('season.json', 'r') as f:
    season = json.load(f)
    print(f"Four seasons are: {season}")

Output:

Four seasons are: Summer, Winter, Spring, Autumn

Finally, we have printed the recovered list of four seasons and it’s the same list created in seasondump.py.  This is the simple way to share data between two programs.



Sample example

Let’s write a program to see the full functionality of how the JSON module (JSON in python) really helps the programmer to store the data and share it with other programmers working in a different programming language.

Example:

# twentyDzongkhag.py

import json
file = 'DzongkhagsOfBhutan.json'
try:
    with open(file, 'r') as f:
        dzo = json.load(f)
        print(f"20 dzongkhags of Bhutan: {dzo}")
except FileNotFoundError:
    dzongkhag = input("Enter the names of 20 Dzongkhags of Bhutan:")
    with open(file, 'w') as f:
        json.dump(dzongkhag, f)

First output:

Enter the names of 20 Dzongkhags of Bhutan: Bumthang, Chukha, Dagana, 
Gasa, Haa, Lhuentse, Mongar, paro, Pema Gatshel, Punakha, Samdrupjongkhar, 
Samtse, Sarpang, Thimphu, Trashigang, Tashiyangtse, Trongsa, Tsirang, 
Wangdi phodrang, Zhemgang

Next time when you run a program, you do not have to enter all the 20 dzongkhag of Bhutan manually. It will be already stored in the ‘DzongkhagsOfBhutan.json‘ file. Data will be read automatically from that file.

20 dzongkhags of Bhutan: Bumthang, Chukha, Dagana, Gasa, Haa, 
Lhuentse, Mongar, paro, Pema Gatshel, Punakha, Samdrup jongkhar, 
Samtse, Sarpang, Thimphu, Trashigang, Tashiyangtse, Trongsa, 
Tsirang, Wangdi phodrang, Zhemgang

Note: We choose a filename with extension .json to store data. It is not compulsory to store in a JSON file format, you can use other file extensions such as txt.


Previous blog post:

File handling in python