Sometimes, we want to fix NumPy array is not JSON serializable with Python.
In this article, we’ll look at how to fix NumPy array is not JSON serializable with Python.
How to fix NumPy array is not JSON serializable with Python?
To fix NumPy array is not JSON serializable with Python, we canm create our encoder class.
For instance, we write
class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)
a = np.array([[1, 2, 3], [4, 5, 6]])
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]}, 
                       cls=NumpyEncoder)
to create the NumpyEncoder class that has the default method.
In it, we check if obj is a NumPy array instance with isinstance.
If it’s true, then we call tolist to convert it to a list.
Otherwise, we return the JSON string with
json.JSONEncoder.default(self, obj)
Then we call json.dumps with NumPy array a and cls set to NumpyEncoder to return the JSON string version of a.
To convert a JSON string to a NumPy array, we write
json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
to call json.loads to load the json_dump string into a dict.
Then we call np.asrray to get the entry in json_load with key 'a' and convert it into a NumPy array.
Conclusion
To fix NumPy array is not JSON serializable with Python, we canm create our encoder class.
