Let us see how to deserialize a JSON document into a Python object. Deserialization is the process of decoding the data that is in JSON format into native data type. In Python, deserialization decodes JSON data into a dictionary(data type in python).
We will be using these methods of the json module to perform this task :Â
Â
- loads() : to deserialize a JSON document to a Python object.
- load() : to deserialize a JSON formatted stream ( which supports reading from a file) to a Python object.
Example 1 : Using the loads() function.Â
Â
Python3
# importing the moduleimport jsonÂ
# creating the JSON data as a stringdata = '{"Name" : "Romy", "Gender" : "Female"}'Â
print("Datatype before deserialization : "Â Â Â Â Â Â + str(type(data)))Â Â # deserializing the datadata = json.loads(data)Â
print("Datatype after deserialization : "Â Â Â Â Â Â + str(type(data))) |
Output :Â
Â
Datatype before deserialization : Datatype after deserialization :
Example 2 : Using the load() function. We have to deserialize a file named file.json.Â
Â
Â
Python3
# importing the moduleimport jsonÂ
# opening the JSON filedata = open('file.json',)Â
print("Datatype before deserialization : "Â Â Â Â Â Â + str(type(data)))Â Â Â Â # deserializing the datadata = json.load(data)Â
print("Datatype after deserialization : "Â Â Â Â Â Â + str(type(data))) |
Output :Â
Â
Datatype before deserialization : Datatype after deserialization :
Â

