Last active
July 6, 2022 07:41
-
-
Save thepushkarp/f5ae8fa7d13bf6f730f917f5f172093b to your computer and use it in GitHub Desktop.
Store a numpy.ndarray or any nested-list composition as JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Link: https://stackoverflow.com/a/47626762/10307491 | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment