Skip to content

Instantly share code, notes, and snippets.

@garybradski
Created December 20, 2018 04:46
Show Gist options
  • Save garybradski/66e5f184702fe71398e13b2f4961a31c to your computer and use it in GitHub Desktop.
Save garybradski/66e5f184702fe71398e13b2f4961a31c to your computer and use it in GitHub Desktop.
Read/write json of numpy array
import numpy as np
import codecs, json
#In order ot store an numpy array as a .json file
a = np.arange(10).reshape(2,5) # a 2 by 5 array
b = a.tolist() # nested lists with same data, indices
# Obviously, if you already have list, you don't/can't .tolist() it
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) #This reads json to list
a_new = np.array(b_new) #This converts to numpy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment