Home > Article > Backend Development > How to Serialize NumPy Arrays in Django for JSON Compatibility?
NumPy Array Serialization Issue with Django
When utilizing NumPy arrays within Django contexts, you may encounter an error stating that the array is not JSON serializable. This occurs because NumPy arrays, by default, cannot be directly represented in JSON format.
Explanation of Serialization
Serialization involves converting objects into a format that can be transmitted over a network or stored persistently. JSON (JavaScript Object Notation) is a popular data format used for both purposes. However, arrays stored in NumPy's native data structure (which aligns with memory optimization) are incompatible with JSON's format.
Solution: Converting to Lists
To resolve this issue, you can convert the NumPy array to a nested list using the .tolist() method. This process creates a list structure that is inherently compatible with JSON serialization.
Code Example
Here's an example of serializing and de-serializing a NumPy array in Python:
<code class="python">import numpy as np import codecs, json # Create a 2D NumPy array a = np.arange(10).reshape(2, 5) # Convert the array to a list b = a.tolist() # Serialize the list using JSON json.dump(b, codecs.open('path.json', 'w', encoding='utf-8'), separators=(',', ':'), sort_keys=True, indent=4) # De-serialize the JSON back to a NumPy array obj_text = codecs.open('path.json', 'r', encoding='utf-8').read() b_new = json.loads(obj_text) a_new = np.array(b_new)</code>
This process converts the NumPy array into a format that can be transmitted over the network and subsequently reconstructed into its original form.
The above is the detailed content of How to Serialize NumPy Arrays in Django for JSON Compatibility?. For more information, please follow other related articles on the PHP Chinese website!