What is Python JSON?
JSON is an acronym for JavaScript Object Notation. Python has a built-in package named ‘json’ to support JSON in Python. JSON is basically used for encoding and decoding data. The process of encoding the JSON data is referred to as serialization as it involves converting data into a series of bytes that can be stored and transmitted between servers and web applications. Since serialization is the encoding the data, we can guess the term used for decoding. Yes, it is deserialization.
In this module, we will learn about JSON in Python and cover the following topics:
So, without further delay, let’s get started.
Become a master of Python by going through this online Python Course in Toronto!
How to Parse JSON in Python?
How to read JSON files in Python?
Reading JSON data from a file is very easy. json.load() method reads the string from a file, parses the JSON data. Then it populates a Python dictionary with the parsed data and returns it back to us.
Example:
#import json in Python
import json
with open('Intellipaat.txt') as json_file:
#load json file python
data = json.load(json_file)
for p in data['Course']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')
How to convert JSON String to Python Object: json.loads()
If we have a JSON string or JSON data, we can easily parse it using the json.loads() method found in the JSON package. To make use of this method, we have to import the JSON package offered by Python. As discussed above, this method is called deserialization, as we are converting the JSON encoded data into Python objects. Deserialization takes place as per the following table.
For example, the JSON data of the object type will be converted into a Python dictionary.
JSON |
Python |
object |
dict |
array |
list |
string |
str |
number (int) |
int |
number (real) |
float |
true |
true |
false |
false |
null |
none |
Example of Parsing Json in Python:
import json
intellipaat = '{"course":"python", "topic":"Python JSON"}'
#parse a JSON string using json.loads()
intellipaat_dict = json.loads(intellipaat)
print(intellipaat_dict)
print(type(intellipaat))
print(type(intellipaat_dict))
Output:
{'course': 'python', 'topic': 'Python JSON'}
<class 'str'>
<class 'dict'>
In the above example, intellipaat is a JSON string and intellipaat_dict is a Python dictionary.
Get 100% Hike!
Master Most in Demand Skills Now!
How to convert Python Object to JSON String: json.dumps()
json.dumps() function converts a Python object into a json string.
import json
Dictionary ={1:'Intellipaat', 2:'Python',3:'Tutorial'}
json_string = json.dumps(Dictionary)
print('Equivalent json string of input dictionary:',
json_string)
print(" ")
print(type(json_string))
The output will be
Equivalent json string of input dictionary: {"1": "Intellipaat", "2": "Python", "3": "Tutorial"}
<class 'str'>
Get certified by this top Python Course in Singapore today!
How to Convert Python Dictionary to JSON?
We can also convert Python data types into JSON format using the json.dumps() method. Let us take a look at the example and understand how to convert Python objects to JSON in Python programming.
Example:
import json
intellipaat = {"course":"python", "topic":"Python JSON"}
intellipaat_json = json.dumps(intellipaat)
print(intellipaat_json)
print(type(intellipaat))
print(type(intellipaat_json))
Output:
{"course": "python", "topic": "Python JSON"}<class 'dict'><class 'str'>
While converting Python objects into JSON, these objects get converted into the equivalent JSON type as per the following table:
Python |
JSON |
dict |
Object |
list |
Array |
tuple |
Array |
str |
String |
int |
Number |
float |
Number |
True |
true |
False |
false |
None |
null |
How to Format the Result of JSON in Python?
Even though we have learned how to convert the Python object into JSON data, it can still be very hard to read the converted JSON data, with no indentation and no line breaks. To make it more readable, there are various parameters of the json.dumps() method that we can use.
Example:
#using indent parameter to provide indentation
json.dumps(b, indent = 3)
We can also include various separators, such as, comma and colon.
Example:
json.dumps(b, indent = 3, separators = (“.”,”=”))
Learn end-to-end Python concepts through the Python Course in Hyderabad to take your career to a whole new level!
Ordering the Result of Json in Python
In certain cases where we might want to sort the resultant JSON data after converting it from Python to JSON, we can simply use another parameter of the json.dumps() method, the sort_keys.
With the help of this parameter, we can define if we want the result to be sorted or not, using values such as true and false.
Example:
json.dumps(b, indent = 3, sort_keys=True)
With this, we come to the end of this module in python Tutorial. You can also go through this blog on Python Data Science tutorial if you want to know why Python is the most preferred language for data science.
Further, check out our offers for Python training Courses and also refer to the trending Python interview questions for freshers prepared by the industry experts.