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.
- class Person:
- name:str
- age: int
- gender: str
- is_student: bool
Below is the code to convert from object to Json.
- import json
-
-
- person = Person()
- person.name = "ABC"
- person.age = 25
- person.gender = "Male"
- person.is_student = True
-
- jsonString:str = json.dumps(person.__dict__, indent=2)
- 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:
Below is the code to convert Json string to object.
- import json
-
-
- jsonString = '{"name": "ABC", "age": 20, "gender": "Male", "is_student": "True"}'
- person.__dict__ = json.loads(jsonString)
- print(f"person.name : {person.name}")
- print(f"person.age : {person.age}")
- print(f"person.gender : {person.gender}")
- 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.
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.