What is deserialize and serialize in JSON?

Viewed 327814

I have seen the terms "deserialize" and "serialize" with JSON. What do they mean?

3 Answers

Serialize and Deserialize

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]

The opposite operation, extracting a data structure from a series of bytes, is deserialization.

Source: wikipedia.org

Explained with Python

In Python serialization does nothing else than just converting the given data structure into its valid JSON pendant (e.g., Python's True will be converted to JSON's true and the dictionary itself will be converted to a string) and vice versa for deserialization.

You can easily spot the difference between Python and JSON representations, e.g., by their Boolean values. Have a look at the following table for the basic types used in both contexts:

Python JSON
True true
False false
None null
int, float number
str (with single ', double " and tripple """ quotes) string (only double " quotes)
dict object
list, tuple array

Code Example

Python builtin module json is the standard way to do serialization and deserialization:

import json

data = {
    'president': {
        "name": """Mr. Presidente""",
        "male": True,
        'age': 60,
        'wife': None,
        'cars': ('BMW', "Audi")
    }
}

# serialize
json_data = json.dumps(data, indent=2)

print(json_data)
# {
#   "president": {
#     "name": "Mr. Presidente",
#     "male": true,
#     "age": 60,
#     "wife": null,
#     "cars": [
#       "BMW",
#       "Audi"
#     ]
#   }
# }

# deserialize
restored_data = json.loads(json_data) # deserialize

Source: realpython.com, geeksforgeeks.org

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

Related