Skip to content

Instantly share code, notes, and snippets.

@costrouc
Created October 13, 2016 18:55
Show Gist options
  • Save costrouc/759c85d72a1dd2731cbc403c1c17ff70 to your computer and use it in GitHub Desktop.
Save costrouc/759c85d72a1dd2731cbc403c1c17ff70 to your computer and use it in GitHub Desktop.
JSONDecode and JSONEncode
import json
class NPEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
class NPDecoder(json.JSONDecoder):
def __init__(self, **kwargs):
json.JSONDecoder.__init__(self, **kwargs)
self.parse_array = self.JSONArray
self.scan_once = json.scanner.py_make_scanner(self)
def JSONArray(self, s_and_end, scan_once, **kwargs):
values, end = json.decoder.JSONArray(s_and_end, scan_once, **kwargs)
return np.array(values), end
# json.dump( ... , cls=NPEncoder)
# json.load( ... , cls=NPDecoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment