Serialization

The pickle module

  • In Python, the pickle module provides a very simple way to serialize and deserialize objects.
  • See the following example:
import pickle

# Example object to serialize
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Serialize the object to a file
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f)

# Deserialize the object from the file
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)

print(loaded_data)

Other serialization formats: JSON and XML

  • JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two other popular standard formats for serialization, similar to pickle but more widely used for interoperability and readability in various programming languages and applications. In other words: it is not restricted to Python.

  • JSON is generally more lightweight and easier to work with in web applications, while XML provides more flexibility and is often used in more complex data exchange scenarios.

JSON

  • A JSON file format would look like this, for example:
{
  "name": "Alice",
  "age": 30,
  "city": "New York"
}
  • JSON can be easily read with the language JavaScript, but also can be handled with Python using built-in module json (see documentation)

XML

  • A XML file would look like this:
<person>
  <name>Alice</name>
  <age>30</age>
  <city>New York</city>
</person>
  • Python can handle XML files using the built-in module xml.etree.ElementTree, or with third-party libraries such as xmltodict or lxml.