How to Serialize NumPy Arrays to JSON in Python?

Linda Hamilton
Release: 2024-11-03 14:18:03
Original
724 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!