NumPy array is not JSON serializable

typeerror: object of type 'ndarray' is not json serializable flask
convert numpy.ndarray to json
object of type 'ndarray' is not json serializable mpld3
object of type int64 is not json serializable
numpy array to list
object of type 'float32' is not json serializable
numpy json encoder
storing numpy array in json

After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable

What does this mean?


I regularly "jsonify" np.arrays. Try using the ".tolist()" method on the arrays first, like this:

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 same data, 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

In order to "unjsonify" the array use:

obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
b_new = json.loads(obj_text)
a_new = np.array(b_new)

Python Serialize NumPy ndarray into JSON, Learn how to solve TypeError: Object of type ndarray is not JSON serializable. Write custom JSON decoder to convert any NumPy array into  Also, some very interesting information further on lists vs. arrays in Python ~> Python List vs. Array – when to use? It could be noted that once I convert my arrays into a list before saving it in a JSON file, in my deployment right now anyways, once I read that JSON file for use later, I can continue to use it in a list form (as opposed to converting it back to an array).


Store as JSON a numpy.ndarray or any nested-list composition.

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]])
print(a.shape)
json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]}, cls=NumpyEncoder)
print(json_dump)

Will output:

(2, 3)
{"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}

To restore from JSON:

json_load = json.loads(json_dump)
a_restored = np.asarray(json_load["a"])
print(a_restored)
print(a_restored.shape)

Will output:

[[1 2 3]
 [4 5 6]]
(2, 3)

Make NDArray JSON serializable? - Performance, TypeError: Object of type 'NDArray' is not JSON serializable. This is not surprising​; numpy.array gives the same error. Then, what is the most  You are here because when you try to encode/serialize NumPy array into a JSON format, you received a TypeError: Object of type ndarray is not JSON serializable. In this article, I will show you how to make NumPy array JSON serializable so that you can convert any NumPy array into JSON formatted data.


You can use Pandas:

import pandas as pd
pd.Series(your_array).to_json(orient='values')

How to serialize a NumPy array into JSON in Python, How to serialize a NumPy array into JSON in Python. Serializing a NumPy array into JSON converts the array to a JSON formatted string. Is it possible to allow numpy scalars in a dataframe? The following code is not working, because a np.array is not json serializable: df_numpy = pd.DataFrame([dict( x=np.array(1), y=np.array(2), )]


I found the best solution if you have nested numpy arrays in a dictionary:

import json
import numpy as np

class NumpyEncoder(json.JSONEncoder):
    """ Special json encoder for numpy types """
    def default(self, obj):
        if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
            np.int16, np.int32, np.int64, np.uint8,
            np.uint16, np.uint32, np.uint64)):
            return int(obj)
        elif isinstance(obj, (np.float_, np.float16, np.float32, 
            np.float64)):
            return float(obj)
        elif isinstance(obj,(np.ndarray,)): #### This is the fix
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

dumped = json.dumps(data, cls=NumpyEncoder)

with open(path, 'w') as f:
    json.dump(dumped, f)

Thanks to this guy.

NumPy, Read As NumPy Array import numpy as np >>> a = np.array([1,2,3]) >>> a array([1, 2, TypeError: array([1, 2, 3]) is not JSON serializable. numpy.ndarray is also not serializable by json.dumps() import numpy as np import json a = np.array([1,2,3,4]) json.dumps(a) #crash json.dumps(a[0]) #this works! msg191890 - (view) Author: R. David Murray (r.david.murray) *. Date: 2013-06-25 23:02. I would (naively) not expect either of these to be serializable.


Use the json.dumps default kwarg:

default should be a function that gets called for objects that can’t otherwise be serialized.

In the default function check if the object is from the module numpy, if so either use ndarray.tolist for a ndarray or use .item for any other numpy specific type.

import numpy as np

def default(obj):
    if type(obj).__module__ == np.__name__:
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return obj.item()
    raise TypeError('Unknown type:', type(obj))

dumped = json.dumps(data, default=default)

(Blessed) JSON serializable format · Issue #12481 · numpy/numpy , if NumPy devs proposed a way to make an array JSON serializable about encoding NumPy arrays as JSON often site that this will not be  PatchCollection - TypeError: array([ 1.]) is not JSON serializable #434. omn14 opened this issue Oct 13, 2017 · 17 comments. I want to make a .html with a plot of some patches in a patch collection.


Submission error: TypeError: Array is not JSON serializable · Issue , sample() is a numpy array, which is not JSON serializable. To debug and see this you could print (or pdb ) suspicious variables from the pointed  Convert numpy.nd array to json [duplicate] Ask Question Asked 3 years ago. NumPy array is not JSON serializable. 35. Convert Pandas DataFrame to JSON format. 30.


Issue 18303: json.dumps() claims numpy.ndarray and numpy.bool_ , ndarray is also not serializable by json.dumps() import numpy as np import json a = np.array([1,2,3,4]) json.dumps(a) #crash  Solution for serializing a numpy array of any dimensions and data types. As far as I know you can not simply serialize a numpy array with any data type and any dimensionbut you can store its data type, dimension and information in a list representation and then serialize it using JSON.


JSON tricks (python), array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable. What does this mean? I regularly "jsonify" np.arrays. Try using the  For the following code: from mxnet import nd import json a = nd.array([[0,1,2],[3,4,5],[6,7,8]]) json.dumps({'a':a}) It gives the following error: TypeError: Object of type 'NDArray' is not JSON serializable This is…