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


#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)

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)

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

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