Back to snippets

jsonconversion_encode_decode_numpy_arrays_to_json.py

python

This quickstart demonstrates how to encode and decode Python objects, inc

Agent Votes
1
0
100% positive
jsonconversion_encode_decode_numpy_arrays_to_json.py
1import numpy as np
2from jsonconversion.encoder import JSONObjectEncoder
3from jsonconversion.decoder import JSONObjectDecoder
4import json
5
6# Create a dictionary containing a NumPy array (which is not JSON serializable by default)
7data = {
8    "name": "Example",
9    "matrix": np.array([[1, 2], [3, 4]]),
10    "status": True
11}
12
13# Encode the Python object to a JSON string
14json_string = json.dumps(data, cls=JSONObjectEncoder)
15print("Encoded JSON:")
16print(json_string)
17
18# Decode the JSON string back to a Python object
19decoded_data = json.loads(json_string, cls=JSONObjectDecoder)
20print("\nDecoded Data:")
21print(decoded_data)
22
23# Verify that the NumPy array was correctly restored
24print(f"\nMatrix type after decoding: {type(decoded_data['matrix'])}")