Introduction to JSON in Python
JSON in Python is a format for storing data. It is referred to as JavaScript Object Notation. It is a lightweight data frame as compared to XML or HTML format. It is simple to understand and looks the same as dictionaries in Python with minor differences like (Boolean notation and Null notation). It is a standard data format for storing data/Fetch [
data from APIs and configuration files. This format is language-independent and is adaptable in python as well. In the case of Python, it has a separate library called JavaScript Object Notation.
How does it work?
As we know, Jason is basically a file format to store the data; now, we can use an existing file or create a new python dataset and assign it in format. The Syntax for each operation is discussed below.
1. Importing JSON Library in Python
Python uses the JavaScript Object Notation library. To Install the library, the syntax is given below.
Syntax:
Pip install jsonlib ;
pip install demjson
Once you have a library in python, write the following command for importing it into code.
Import json;
2. Get or Load JSON Format Dataset
To load JSON format data, the following syntax is used as given below.
Syntax:
My_json = json.load( Mason )
In parenthesis, write the name of the file you want to load.
3. Perform Operations on It
JSON format is like dictionaries of python with some minor differences. We can perform several operations that we can perform on python dictionaries like viewing datasets, using loops, changing values, aggregating different keys to create a new key, etc.
4. Return JSON Format from Python
When we load the JSON file into python, it is converted to python readable format and is being worked upon. Once the file is ready, it is again converted to the original JSON format.
To do this, we use the following Syntax as given below:
Syntax:
My_json_output = json.dump( Mjson )
In parenthesis, write the file name you would like to dump.
How to Convert JSON to Python and Python to JSON?
This is the most important part of this article. To convert a JSON document into python, we perform Deserialization or Decoding. To convert a python document into json string, we perform Serialization or Encoding. To perform these two operations, we need a library called demjson.
Serialization and Deserialization provide a translator that encodes and decodes the format. The below table shows the relation between python and JSON.
Here we can see some differences that we can identify clearly: numbers in JSON are treated as int and float, null in JSON is treated as None in Python, objects in JSON are dictionaries in python, and so on. We will see the conversion in detail in the example section.
Examples
Here are the examples as follows:
Encoding / Serialization to JSON File
The task is to create one standard python dictionary and then encode the same into a file. Here we will take the None and false type from python and observe how the same has been changed in a file.
Code:
import json
#Creating a Dictionary Dataset in python
Mjson= { 'City' : ['Hyd' , 'Delhi' , 'Bombay' , 'Indore', None],
'Food' :['Biryani', 'Momos' , 'Vadapav' , 'Poha' , False]}
# Encoding to json file.
with open("Mjson.json", "w") as write_file:
json.dump(Mjson, write_file)
After executing this code check in the directory of python code, the Mjson.json file would have been created.
Output:
Observe None is changed to null, and False is changed to false.
Decoding / Deserialization to Python
The Mjson file which we just now have created, we will decode the same to python again. We will observe the previous observation once again.
Code:
import json;
# Decoding json into python
Import json
with open("Mjson.json", "r") as read_file:
My_python = json.load(read_file)
My_python
The output of the above will be our python dictionary. Observe the null again is converted to None.
Output:
Formatting of JSON String Using Python Encoder
While encoding JSON, we can use some specified format defined to maintain clarity & format of data. Here we will use separators, indent and sort keys. As we already have a JSON file, we will modify the existing one.
Code:
with open("Mjson.json", "w") as write_file:
json.dump(Mjson, write_file, indent= 4, sort_keys =True, separators = (" | " , " = " ) )
Output:
It’s purely the choice of coder how JSON format is required.
Advantages
Let’s see some of the advantages in detail given below:
- JSON is a formation to transfer data from server to client and vice versa. HTML and XML provide static data, while most of the data we need is dynamic; in this case, it can help.
- When an Asynchronous request is sent to a server via browser or application, the server receives the request and returns data (whatever format is acceptable, the client needs data oIfow, if the format is Html format, it will give design as well as data, but the client already has designed it; it requires only data.
- In the server, the data will be in the form of objects with properties, making data complex data-type objects. Now for this, we have JavaScript Object Notation. JavaScript Object Notation makes processing complex data with multiple classes and objects easy.
- It is of utmost need to use JSON type in DS and ML research; python provides solutions for the same. Server Serialise the objects, and the client de-serializes them and reads them.
Conclusion – JSON in Python
JavaScript Object Notation is a format generally produced from different java scripts and APIs. With python, one can communicate JSON files. In python, Deserialization or decoding is used to convert a json object into a python dictionary. Serialization or encoding is used for converting a python doc into a json object. This article covers both formats.
Recommended Articles
This is a guide to JSON in Python. Here we have discussed how it works in Python along with various examples and its advantages in detail. You may also look at the following articles to learn more-
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses