If you are coming up to read this article, perhaps you have come up with a situation where you need to store your data into a structured format which could easily be transported between web apps and servers.
JSON stands for Java Script Object Notation which as said above is a data format that is really very light weight and is pretty similar with Python Dictionary objects. They are really very useful since the web apps and APIs could easily parse through them and quickly transport the data between apps and services. In this article we will use the python “json” package to convert a python object into a JSON object.
Before diving deep into the blog, clear the basics of python; First Step Towards Python.
JSON objects are often stored with keys and values format which is similar to the dictionary.
{
"key1" : "value1",
"key2" : "value2",
.
.
.
}
The first thing we need to do is install the “json” package in python. The “json” package allows us to convert python objects into JSON objects. Following is the syntax to install the “json” package in the python environment.
#Importing JSON Package in Python
import json
Please note that the method of converting python objects into JSON is called serialization. It is because when we convert a python object into a JSON (and vice versa), it is a process of storing the data into a series of bytes.
There are four different methods in the python json module to work with python objects and JSON altogether. Those four are mentioned as below:
When your computer is processing lots of information of various data types, it needs a data dump to process that information. Therefore, we have dumps() and dump() methods under python.
(Also read: Data Types in Python)
Following is the table of conversion for python objects into equivalent JSON objects. It's pretty much straight forward, but needed to be shown.
Python Object |
Equivalent JSON Object |
String (str) |
string |
Integer (int) |
Number - int |
Floating point number (float) |
Number - real |
Boolean True (True) |
true |
Boolean False (False) |
false |
list |
array |
tuple |
array |
dictionary |
object |
None |
Null |
Now, we will move towards some examples where we use the methods mentioned above to convert a python object into an equivalent JSON object and vise-versa.
(Must catch: Python to Represent Output)
The json.dumps() method allows us to convert a python object into an equivalent JSON string object. This is really useful while feeding information to the APIs which needs to be parsed or printed. See an example below:
#Importing JSON Package in Python
import json
#creatig a dictionary which can be converted into JSON string
my_details = {
"Name" : "Lalit Salunkhe",
"Age" : 28,
"Job" : True,
"Married" : False,
"Bikes" : [
{"Model1": "Jupiter 120", "price": 62000},
{"Model2": "Yamaha YZF-R15", "price": 150000}
]
}
print(json.dumps(my_details))
Here, we have created a python dictionary and used json.dumps() method to convert it into a JSON string object.
See the output as shown below:
Output of python to JSON conversion
We can use other functions too, in order to amend the code such that it can be sorted ascendingly and indented.
#Sorting the results into ascending order and indenting
print(json.dumps(my_details, indent = 3, sort_keys= True))
See now the updated output as shown below:
Python object to JSON ordered and with indentations
Here, you could see how the output is sorted in ascending order where the key “Age” and equivalent value appears first rather than the key “Name” and value associated with it. This is because we used the sort_keys = True argument which allows us to sort the result in ascending order. Besides, you could also see how the output is now indented with each line as we have used the indent = 3 argument within the code.
Also, apart from all this, how could we make sure that the conversion (python object to JSON string) has actually happened? Well, we can always use the type() function to know the class of the object. See the code below for a better realization.
#checking class of the object
print(type(json.dumps(my_details, indent = 3, sort_keys= True)))
Now, if you see the output, it should look something as shown below:
Checking class of the JSON object
You can easily see that the entire object my_details, which was a python dictionary before, is now converted into a JSON object with class type string.
(Read also: Word embedding in NLP using Python)
In addition to json.dumps(), json.dump() method allows us to convert the given python object into an equivalent JSON object and then stores the result in a text file. We are going to use the same Example as above for this one
import json
my_details = {
"Name" : "Lalit Salunkhe",
"Age" : 28,
"Job" : True,
"Married" : False,
"Bikes" : [
{"Model1": "Jupiter 120", "price": 62000},
{"Model2": "Yamaha YZF-R15", "price": 150000}
]
}
#Using file I/O operation to create a new json file into working directory
with open("Data_File.json", "w") as file:
#Using json.dump() to write the data into a JSON file.
json.dump(my_details, file)
Here, we have used the file input output operation to create a new JSON file with the name “Data_File.json”. This file will be used to store a python dictionary named my_details as a JSON string, when we hit the json.dump() method.
Also, there is nothing we could show you as an output in the python console. However, on the working directory of your python, you could see a json file with name Data_File. See the screenshot below:
Data_File is created on working python directory
If you open the JSON file into any text editor, you will see a JSON string with the data equivalent to my_details under it as shown below.
Output of the Data_File looks like this
(Recommended blog: Python Essentials for Voice Control: Part 1)
In order to convert (decode) JSON strings into equivalent python objects, we have json.loads() and jso.load() methods, which we have described earlier at the start of this article itself. Decoding look as below:
JSON Object |
Equivalent Python Object |
Null |
None |
Object |
Dictionary |
array |
list |
Boolean false (False) |
False |
Boolean true (True) |
True |
Number - int |
int |
Number - real |
Float |
string |
String (str) |
We are now going towards the examples which will help us to decode the JSON data into equivalent python objects.
The json.loads() method allows you to convert a JSON string into an equivalent python object (Specifically a python dictionary). See the code below:
#Importing JSON Package in Python
import json
#JSON string my_details_json being printed
print(type(my_details_json))
#Decoding a JSON string into a python dictionary with json.loads() method
my_details_dict = json.loads(my_details_json)
print(type(my_details_dict)) #To check if conversion worked
Here, we have a json object named my_details_json. We can have used the type() function to check whether it is actually a json string or not. After that, we have used the json.loads() method to decode the json object into an equivalent python dictionary and checked it’s type as well (it should be dict). See the output as shown below:
Conversion of JSON string into an equivalent Python Dictionary
Now, we will see an example where we use the json.load() methods to convert/decode a JSON file into a python object (dictionary). Remember, in example 2, we have created a JSON file named Data_File.json. We will use the same file as a source into this example and apply the json.load() method to decode it into a python dictionary. See the example below:
#Importing JSON Package in Python
import json
#Using python I/O open function to read the json file named Data_File.
with open("C:/Users/lsalunkhe/.spyder-py3/Data_File.json") as file:
#Using json.load() to deserialize a python object into python object
Py_object = json.load(file)
print(Py_object)
print(type(Py_object))
Here, we are using the python built-in I/O open function to read the json file name Data_File and then using json.load() to convert the data from that file into a relevant python object (i.e. a dictionary). See the output below:
Converting a data from json file object into a python object using json.load() method
Well, we will end this article here with following summary points
(Recommended blog: How Do We Implement Beautiful Soup For Web Scraping?)
The json.dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json.
The json.dump() method allows us to convert a python object into an equivalent JSON object and store the result into a JSON file at the working directory.
(Must read: 20 Python interview questions)
The json.loads() method allows us to convert a JSON string into an equivalent python object (dictionary). In other words, it helps us to receive the data from json to python.
The json.load() method allows us to read a JSON data file and then convert the data into an equivalent python data object.
5 Factors Influencing Consumer Behavior
READ MOREElasticity of Demand and its Types
READ MOREAn Overview of Descriptive Analysis
READ MOREWhat is PESTLE Analysis? Everything you need to know about it
READ MOREWhat is Managerial Economics? Definition, Types, Nature, Principles, and Scope
READ MORE5 Factors Affecting the Price Elasticity of Demand (PED)
READ MORE6 Major Branches of Artificial Intelligence (AI)
READ MOREScope of Managerial Economics
READ MOREDijkstra’s Algorithm: The Shortest Path Algorithm
READ MOREDifferent Types of Research Methods
READ MORE
Latest Comments
hmehdizadeh68
Feb 05, 2023thank you