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.
Copy
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.
Copy
3. XML Serialization with xml.etree.ElementTree
Converting Python data structures to XML format.
Copy
4. XML Deserialization with xml.etree.ElementTree
Parsing an XML file into Python objects.
Copy
5. Pickling: Binary Serialization with pickle
Using pickle to serialize Python objects into binary format.
Copy
6. Custom Serialization with pickle
Implementing custom serialization using pickle.
Copy
7. YAML Serialization with PyYAML
Using PyYAML for YAML serialization.
Copy
8. YAML Deserialization with PyYAML
Deserializing YAML into Python objects.
Copy
9. MessagePack: Efficient Binary Serialization
Using msgpack for efficient binary serialization (requires the msgpack library).
Copy
10. Custom JSON Serialization with json
Customizing the JSON serialization by overriding the default method.
Copy
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