Skip to content

Instantly share code, notes, and snippets.

@secemp9
Created December 19, 2023 14:03
Show Gist options
  • Save secemp9/f8d7f18750b8d2cb65e3e49b2961580f to your computer and use it in GitHub Desktop.
Save secemp9/f8d7f18750b8d2cb65e3e49b2961580f to your computer and use it in GitHub Desktop.
numpy instance serialize
import sys
import json
import numpy as np
def improved_default(data):
"""
Improved function to handle numpy data types for JSON serialization.
Converts numpy integer and float types to their native Python counterparts.
"""
if isinstance(data, np.integer):
return int(data)
elif isinstance(data, np.floating):
return float(data)
else:
raise TypeError(f"Can't serialize {data!r}")
def improved_json_serialize(data):
return json.dumps(data, default=improved_default)
# Example usage of the improved serialization function
if __name__ == "__main__":
# Create numpy data types for testing
numpy_int32_data = np.int32(10)
numpy_float_data = np.float32(10.5)
# Test JSON serialization with the improved function
try:
serialized_int32 = improved_json_serialize(numpy_int32_data)
print(f"Serialized numpy.int32: {serialized_int32}")
except Exception as e:
print(f"Error serializing numpy.int32: {e}")
try:
serialized_float = improved_json_serialize(numpy_float_data)
print(f"Serialized numpy.float32: {serialized_float}")
except Exception as e:
print(f"Error serializing numpy.float32: {e}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment