Serialization & Deserialization in Python

Serialization & Deserialization in Python

·

2 min read

Serialization and deserialization are the processes for transferring data between different systems or storing it persistently. In Python, we can achieve serialization and deserialization using various modules, but one of the most commonly used ones is the json module, which provides functions for encoding Python objects into JSON strings (serialization) and decoding JSON strings into Python objects (deserialization).

Serialization (Encoding)

Serialization is the process of converting Python objects into JSON strings. In this process, the internal representation of Python objects, such as dictionaries, lists, strings, numbers, booleans, and None, is converted into a string format that adheres to the JSON (JavaScript Object Notation) standard. This conversion enables the data to be easily transmitted or stored in a format that is platform-independent and human-readable.

The json module in Python provides functions for serialization (json.dumps()) making it straightforward to convert Python objects to and from JSON strings.

import json
data = {
    "name": "Subin", "age": 25,"is_student": False, "grades": [54, 23]
}
json_string = json.dumps(data)
print(json_string)

we can also convert them and save it in a file with json.dump

import json
"name": "Subin", "age": 25,"is_student": False, "grades": [54, 23]
with open('data.json', 'w') as f:
    json.dump(data, f)

Output:

When a Python object is converted to a JSON object, there are several things to notice

JSONPython
nullNone
falseFalse
trueTrue
numberint long float
objectdict
arraylist tuple
{"name": "Subin", "age": 25, "is_student": false, "grades": [54, 23]}

In this example, the dictionary data is serialized to a JSON string using json.dump(). The resulting JSON string represents the dictionary's key-value pairs as a JSON object.

Deserialization (Decoding)

Deserialization is the process of converting JSON strings into Python objects.

json_string ='{"name": "Subin", "age": 25, "is_student": false, "grades": [54, 23]}'

view = json.loads(json_string)

print(view)

Output:

"name": "Subin", "age": 25,"is_student": False, "grades": [54, 23]

Conclusion

  • The json.dumps() function is used for serialization (encoding), which takes a Python object as input and returns a JSON string.

  • The json.loads() function is used for deserialization (decoding), which takes a JSON string as input and returns a Python object.

  • The json module provides additional functions for handling more complex cases, such as encoding and decoding from files (json.dump() and json.load()).