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.
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)
import xml.etree.ElementTree as ET
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Create the root element
root = ET.Element("person")
# Adding child elements
for key, value in data.items():
child = ET.SubElement(root, key)
child.text = str(value)
# Convert to string
tree = ET.ElementTree(root)
tree.write("data.xml")
import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
data = {}
for child in root:
data[child.tag] = child.text
print(data)
import pickle
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Serialize Python object to binary file
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
# Deserialize Python object from binary file
with open('data.pkl', 'rb') as f:
loaded_data = pickle.load(f)
print(loaded_data)
import pickle
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def __repr__(self):
return f'Person(name={self.name}, age={self.age}, city={self.city})'
def __getstate__(self):
# Custom serialization logic
return (self.name, self.age, self.city)
def __setstate__(self, state):
# Custom deserialization logic
self.name, self.age, self.city = state
person = Person("Alice", 30, "New York")
# Serialize custom object
with open('person.pkl', 'wb') as f:
pickle.dump(person, f)
# Deserialize custom object
with open('person.pkl', 'rb') as f:
loaded_person = pickle.load(f)
print(loaded_person)
import yaml
data = {"name": "Alice", "age": 30, "city": "New York"}
# Serialize to YAML string
yaml_data = yaml.dump(data)
print(yaml_data)
# Save to a file
with open('data.yaml', 'w') as f:
yaml.dump(data, f)
import yaml
yaml_data = """
name: Alice
age: 30
city: New York
"""
# Deserialize YAML string to Python object
data = yaml.safe_load(yaml_data)
print(data)
# Read from a file
with open('data.yaml', 'r') as f:
data_from_file = yaml.safe_load(f)
print(data_from_file)
import msgpack
data = {"name": "Alice", "age": 30, "city": "New York"}
# Serialize to MessagePack
packed_data = msgpack.packb(data)
# Save to a file
with open('data.msgpack', 'wb') as f:
f.write(packed_data)
# Deserialize from MessagePack
with open('data.msgpack', 'rb') as f:
unpacked_data = msgpack.unpackb(f.read())
print(unpacked_data)
import json
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
def __repr__(self):
return f'Person(name={self.name}, age={self.age}, city={self.city})'
def to_dict(self):
return {"name": self.name, "age": self.age, "city": self.city}
# Custom serialization function
def person_serializer(obj):
if isinstance(obj, Person):
return obj.to_dict()
raise TypeError("Type not serializable")
person = Person("Alice", 30, "New York")
# Serialize custom object
json_data = json.dumps(person, default=person_serializer)
print(json_data)
# Deserialize back to Person object
data = json.loads(json_data)
person_obj = Person(**data)
print(person_obj)