How to fix the ‘NumPy array is not JSON serializable’ issue with Python?

Sometimes, we want to fix the ‘NumPy array is not JSON serializable’ issue with Python.

In this article, we’ll look at how to fix the ‘NumPy array is not JSON serializable’ issue with Python.

How to fix the ‘NumPy array is not JSON serializable’ issue with Python?

To fix the ‘NumPy array is not JSON serializable’ issue with Python, we can use the json.dump method with the codecs.open method and the NumPy array’s tolist method.

For instance, we write:

import numpy as np
import codecs, json

a = np.arange(10).reshape(2, 5)
b = a.tolist()
file_path = "data.json"
json.dump(b,
          codecs.open(file_path, 'w', encoding='utf-8'),
          separators=(',', ':'),
          sort_keys=True,
          indent=2)

We create an array with numbers 0 to 9 with np.arange(10).

And we convert that to a 2×5 array with reshape(2, 5).

Next, we call a.tolist to convert the a NumPy array to a list.

Then we call json.dump with b, the file to write to, the separators to insert between entries, whether to sort keys, and the number of spaces to indent to generate the JSON file from the b list.

codecs.open opens the data.json for writing.

And so data.json has:

[
  [
    0,
    1,
    2,
    3,
    4
  ],
  [
    5,
    6,
    7,
    8,
    9
  ]
]

Conclusion

To fix the ‘NumPy array is not JSON serializable’ issue with Python, we can use the json.dump method with the codecs.open method and the NumPy array’s tolist method.