Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I preserve Python tuples with JSON?
JSON format doesn't have a built-in tuple type, so Python's json module converts tuples to JSON arrays (lists). This means the immutability of tuples is lost during serialization. However, you can preserve tuples using custom encoders and decoders or alternative serialization methods.
Problem: Default JSON Conversion
By default, Python tuples are converted to JSON arrays ?
import json
data = {
"coordinates": (10, 20),
"colors": ["red", "blue"],
"dimensions": (1920, 1080, 32)
}
json_string = json.dumps(data)
print("JSON string:", json_string)
# When loaded back, tuples become lists
loaded_data = json.loads(json_string)
print("Loaded data:", loaded_data)
print("Type of coordinates:", type(loaded_data["coordinates"]))
JSON string: {"coordinates": [10, 20], "colors": ["red", "blue"], "dimensions": [1920, 1080, 32]}
Loaded data: {'coordinates': [10, 20], 'colors': ['red', 'blue'], 'dimensions': [1920, 1080, 32]}
Type of coordinates: <class 'list'>
Method 1: Using Custom Encoder and Decoder
Create custom JSON encoder and decoder classes to preserve tuple types ?
import json
class TupleEncoder(json.JSONEncoder):
def encode(self, obj):
def convert_tuples(item):
if isinstance(item, tuple):
return {"__tuple__": True, "items": list(item)}
elif isinstance(item, list):
return [convert_tuples(i) for i in item]
elif isinstance(item, dict):
return {key: convert_tuples(value) for key, value in item.items()}
return item
return super().encode(convert_tuples(obj))
def tuple_decoder(dct):
if "__tuple__" in dct:
return tuple(dct["items"])
return dct
# Example usage
data = {
"coordinates": (10, 20),
"colors": ["red", "blue"],
"dimensions": (1920, 1080, 32)
}
# Serialize with tuple preservation
json_string = json.dumps(data, cls=TupleEncoder)
print("JSON string:", json_string)
# Deserialize with tuple restoration
loaded_data = json.loads(json_string, object_hook=tuple_decoder)
print("Loaded data:", loaded_data)
print("Type of coordinates:", type(loaded_data["coordinates"]))
JSON string: {"coordinates": {"__tuple__": true, "items": [10, 20]}, "colors": ["red", "blue"], "dimensions": {"__tuple__": true, "items": [1920, 1080, 32]}}
Loaded data: {'coordinates': (10, 20), 'colors': ['red', 'blue'], 'dimensions': (1920, 1080, 32)}
Type of coordinates: <class 'tuple'>
Method 2: Using Pickle (Binary Format)
Pickle preserves all Python data types but creates binary files, not JSON ?
import pickle
data = {
"coordinates": (10, 20),
"colors": ["red", "blue"],
"dimensions": (1920, 1080, 32)
}
# Serialize to binary format
pickled_data = pickle.dumps(data)
print("Pickled data type:", type(pickled_data))
# Deserialize from binary format
loaded_data = pickle.loads(pickled_data)
print("Loaded data:", loaded_data)
print("Type of coordinates:", type(loaded_data["coordinates"]))
Pickled data type: <class 'bytes'>
Loaded data: {'coordinates': (10, 20), 'colors': ['red', 'blue'], 'dimensions': (1920, 1080, 32)}
Type of coordinates: <class 'tuple'>
Comparison
| Method | Output Format | Web Compatible | Preserves Tuples |
|---|---|---|---|
| Default JSON | JSON text | Yes | No |
| Custom Encoder | JSON text | Yes | Yes |
| Pickle | Binary | No | Yes |
Conclusion
Use custom JSON encoders/decoders to preserve tuples in web-compatible JSON format. Use pickle only for local storage or when binary format is acceptable, as it's not suitable for web APIs.
Advertisements
