Serialization And Deserialization (JSON) Using Python

Introduction

 
Serialization
 
Converting the state of an object in to formatted text (json, xml, etc.) is called Serialization
 
Deserialization
 
Converting a formatted text (json, xml, etc.) into the state of an object is called Deserialization.
 
We will see with an example by converting object to Json and Json to object.
 
For this we will use json package (import json).
 
First we will create one class Person to refer as object , Below is the Person class.
  1. class Person:  
  2.     name:str  
  3.     age: int  
  4.     gender: str  
  5.     is_student: bool  
Below is the code to convert from object to Json.
  1. import json  
  2.   
  3. #Serialization  
  4. person = Person()  
  5. person.name = "ABC"  
  6. person.age = 25  
  7. person.gender = "Male"  
  8. person.is_student = True  
  9.   
  10. jsonString:str = json.dumps(person.__dict__, indent=2)  
  11. print(jsonString)  
In the above code we can see that we have defined person class with name, age, gender, is_student.
 
And using json.dumps method to convert it to object to json format. This phenomenon is known as serialization. And while converting pass object.__dict__ as input make "Object of type Person is JSON serializable". else we will get error “Object of type Person is not JSON serializable”
 
Below is the output snap from terminal, In output snap we can see the person object we converted to text i.e. in json format:
 
Serialization And Deserialization(JSON) Using Python
 
Below is the code to convert Json string to object.
  1. import json  
  2.   
  3. #De-Serialization  
  4. jsonString = '{"name": "ABC", "age": 20, "gender": "Male", "is_student": "True"}'  
  5. person.__dict__ = json.loads(jsonString)  
  6. print(f"person.name : {person.name}")  
  7. print(f"person.age : {person.age}")  
  8. print(f"person.gender : {person.gender}")  
  9. print(f"person.is_student : {person.is_student}")  
In the above code we can see that, we have used Json.loads to covert Json string to dictionary object and after that assign it to person.__dict__ to deserialize in to Person object.
 
Below is the output snap from terminal. In output snap we can see that from deserialized object we are able to access name, age, gender and is_student Property.
 
Serialization And Deserialization(JSON) Using Python
 
Summary
 
From this blog we understood about serialization and deserialization. We can serialize object into Json, XML, Yaml and vice versa. We will see more about it in upcoming days.