Search code examples
pythonjsondjangonumpy

NumPy array is not JSON serializable


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?


Solution

  • 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)