Serialize Python Object to String and Deserialize It to Object for Python Beginners – Python Tutorial

By | July 17, 2019

Serializing a python object can allow us to save it into a database or transfer it on internet, when we need use it, we also can deserialize it to python object. In this tutorial, we will introduce how to serialize and deserialize a python object.

serialize and deserialize python object

Preliminaries

#load library
import json

Create a python object to serialize

member={'name':'John', 'sex': 'man', 'age': 32}

Serialize python object to string

seria_memeber = json.dumps(member)
print(type(seria_memeber))
print(seria_memeber)

From the result, we will find python object member is serialized to string.

The resutl is:

<class 'str'>
{"age": 32, "sex": "man", "name": "John"}

Deserialize python string to object

deseria_member = json.loads(seria_memeber)
print(type(deseria_member))
print(deseria_member)

From the resutl, we will find the python object member is restored.

<class 'dict'>
{'sex': 'man', 'age': 32, 'name': 'John'}

Leave a Reply

Your email address will not be published. Required fields are marked *