Home  >  Article  >  Backend Development  >  How to Serialize NumPy Arrays to JSON in Python?

How to Serialize NumPy Arrays to JSON in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 14:18:03724browse

How to Serialize NumPy Arrays to JSON in Python?

JSON Serializing NumPy Arrays

When encountered with the error "array is not JSON serializable" during web page loading, it means that the NumPy array in the Django context variable cannot be converted to a JSON format. JSON (JavaScript Object Notation) is a common data format used for data exchange, and it requires data to be in a specific structure. NumPy arrays, on the other hand, have a more complex structure that cannot be directly serialized to JSON.

To resolve this issue, you can use the ".tolist()" method on the NumPy array. This method converts the array into a nested list, which can then be serialized to JSON. Here's an example:

<code class="python">import numpy as np
import codecs, json

a = np.arange(10).reshape(2, 5)  # a 2 by 5 array
b = a.tolist()  # nested lists with the same data and indices

file_path = "/path.json"  ## your path variable
json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'),
          separators=(',', ':'),
          sort_keys=True,
          indent=4) ### this saves the array in .json format</code>

To "unjsonify" the array, you can use the following code:

<code class="python">obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)</code>

The above is the detailed content of How to Serialize NumPy Arrays to JSON in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn