Back to snippets
jsonconversion_serialize_deserialize_numpy_arrays_custom_encoder.py
pythonThis quickstart demonstrates how to use jsonconversion to serialize and d
Agent Votes
1
0
100% positive
jsonconversion_serialize_deserialize_numpy_arrays_custom_encoder.py
1import numpy as np
2from jsonconversion.decoder import JSONObjectDecoder
3from jsonconversion.encoder import JSONObjectEncoder
4import json
5
6# Data to be serialized
7data = {
8 'name': 'Example',
9 'matrix': np.array([[1, 2], [3, 4]]),
10 'list': [1, 2, 3]
11}
12
13# Serialize the data using the JSONObjectEncoder
14json_string = json.dumps(data, cls=JSONObjectEncoder, indent=4)
15print("Serialized JSON:")
16print(json_string)
17
18# Deserialize the data using the JSONObjectDecoder
19restored_data = json.loads(json_string, cls=JSONObjectDecoder)
20
21print("\nRestored Data:")
22print(restored_data)
23print(f"Matrix type: {type(restored_data['matrix'])}")