Created
May 3, 2023 10:04
-
-
Save daguiam/04d37cc2f9b90e144bf360b6843be8d1 to your computer and use it in GitHub Desktop.
Saves and loads python dictionaries to 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
import json | |
import numpy as np | |
from json import JSONEncoder | |
def open_data_file(filename): | |
# Load data from json file | |
with open(filename, 'r') as fp: | |
json_dict = json.load(fp) | |
return json_dict | |
class NumpyArrayEncoder(JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, np.ndarray): | |
return obj.tolist() | |
return JSONEncoder.default(self, obj) | |
def save_data_file(data_dict, filename, indent=4): | |
""" Saves dictionary to filename""" | |
with open(filename, 'w') as fp: | |
json.dump(data_dict, fp, cls=NumpyArrayEncoder, indent=indent) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment