199. Data Serialization

Here are 10 Python code snippets covering various data serialization methods, including JSON, XML, and binary formats for storage or communication:


1. JSON Serialization

Serializing Python objects into JSON format using the json module.

import json

data = {"name": "Alice", "age": 30, "city": "New York"}

# Convert Python object to JSON string
json_data = json.dumps(data)
print(json_data)

# Save to a file
with open('data.json', 'w') as f:
    json.dump(data, f)

2. JSON Deserialization

Deserializing JSON data back into Python objects.

import json

# JSON string
json_data = '{"name": "Alice", "age": 30, "city": "New York"}'

# Convert JSON string to Python object
data = json.loads(json_data)
print(data)

# Read from a file
with open('data.json', 'r') as f:
    data_from_file = json.load(f)
    print(data_from_file)

3. XML Serialization with xml.etree.ElementTree

Converting Python data structures to XML format.


4. XML Deserialization with xml.etree.ElementTree

Parsing an XML file into Python objects.


5. Pickling: Binary Serialization with pickle

Using pickle to serialize Python objects into binary format.


6. Custom Serialization with pickle

Implementing custom serialization using pickle.


7. YAML Serialization with PyYAML

Using PyYAML for YAML serialization.


8. YAML Deserialization with PyYAML

Deserializing YAML into Python objects.


9. MessagePack: Efficient Binary Serialization

Using msgpack for efficient binary serialization (requires the msgpack library).


10. Custom JSON Serialization with json

Customizing the JSON serialization by overriding the default method.


Conclusion:

These snippets cover a variety of serialization techniques in Python, from standard methods like JSON and XML to more efficient options like MessagePack and custom serialization with pickle. Depending on the use case, you can choose the appropriate format for storing and transmitting data, such as for storage, APIs, or inter-process communication.

Last updated