Save dict of np-arrays to json file

Viewed 843

I've got the following dict:

pts_final_dict
Out[4]: 
{'Zone1': array([[ 40,   0],
        [234, 178],
        [265, 181],
        [312, 181],
        [353, 177],
        [480,   0]]),
 'Zone2': array([[480,   0],
        [520, 173],
        [599, 174],
        [666, 175],
        [724, 182],
        [920,   0]]),
 'Zone3': array([[234, 178],
        [265, 181],
        [312, 181],
        [353, 177],
        [480, 480],
        [ 40, 480]]),
 'Zone4': array([[520, 173],
        [599, 174],
        [666, 175],
        [724, 182],
        [920, 480],
        [480, 480]])}

I never used json before, so my first try is this:

import json
out_file = open("myfile.json", "w") 
json.dump(pts_final_dict, out_file, indent = 6) 
out_file.close() 

I get the error:

TypeError: Object of type ndarray is not JSON serializable.

How can I fix this? I want to store this dict in a json-file, so I can use it again in another script. Thank you

1 Answers

try to change type of values (numpy array to list):

pts_final_dict = {k:v.tolist() for k,v in pts_final_dict.items()}
Related