7) d. JSON

The JavaScript Object Notation is a very widely used serialization schema. It is used a lot in web communication as well as just for simple local storage of structured data.

This is what a JSON data looks like. It is human-readable, has data arranged in a hierarchical fashion and consists of attribute-value pairs which have useful information.



So what do we want to do using the JSON format? The JSON is a simple data format that can easily be stored into a file.

The built-in JSON module provides you the tools to serialize and deserialize data to and from JSON format.

In other words, you can store your variables into a file and load it back again by serializing them. But what is serialization? In simple words, serialization is a process of converting your complex data (what your variables store) and to convert it into a simpler data that can be stored into a file.

To understand this better, imagine if you ordered a DIY furniture set online. The company shipped you a box (or multiple boxes) which contained all the individual parts of your furniture (simple data) and instructions. You used those instructions to assemble your furniture (complex data).

In the same way you can store your variables into a file by serializing them into a format that can be easily written into a file.

1
2
3
4
5
6
7
8
9
10
11
import json

my_dict = {"a": 1, "b": 2, "c": 3}

# Storing my_dict into a file
with open("structured_data.json", "w") as file:
    json.dump(my_dict, file)  # takes an object that you want to store and a file object

# Retrieving my_dict from the file
with open("structured_data.json", "r") as file:
    data = json.load(file)  # takes a file object as an argument



Storing and retrieving the values is quite simple. However, what if you wanted to store multiple values into the same file? Instead of using json.dump which writes directly to a file, you can use json.dumps which creates a string that you can write.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import json

my_dict = {"a": 1, "b": 2, "c": 3}
my_dict2 = {"d": 1, "e": 2, "f": 3}

# Storing my_dict into a file in JSON format.
with open("structured_data.json", "w") as file:

    variable_in_json = json.dumps(my_dict)  # takes an object and converts it into a string in JSON format

    file.write(my_dict_in_json + "\n")

# Retrieving data from JSON to Python dictionary.
with open("structured_data.json", "r") as file:

    variable_in_json = file.readline() #The first line contains the JSON value we had stored earlier.

    my_dict = json.loads(variable_in_json)  # takes a string as an argument



The following image brings out the difference between json.dump and json.dumps methods.