8000 Restored JSON output of dicts with non-string keys by s-kuberski · Pull Request #179 · fjosw/pyerrors · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Restored JSON output of dicts with non-string keys #179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions pyerrors/input/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,27 @@ def write_Corr_to_dict(my_corr):
else:
raise Exception("Unkown datatype.")

def _jsonifier(o):
if isinstance(o, np.int64):
return int(o)
raise TypeError('%r is not JSON serializable' % o)
def _jsonifier(obj):
if isinstance(obj, dict):
result = {}
for key in obj:
if key is True:
result['true'] = obj[key]
elif key is False:
result['false'] = obj[key]
elif key is None:
result['null'] = obj[key]
elif isinstance(key, (int, float, np.floating, np.integer)):
result[str(key)] = obj[key]
else:
raise TypeError('keys must be str, int, float, bool or None')
return result
elif isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
else:
raise ValueError('%r is not JSON serializable' % (obj,))

if indent:
return json.dumps(d, indent=indent, ensure_ascii=False, default=_jsonifier, write_mode=json.WM_SINGLE_LINE_ARRAY)
Expand All @@ -200,7 +217,8 @@ def _jsonifier(o):


def dump_to_json(ol, fname, description='', indent=1, gz=True):
"""Export a list of Obs or structures containing Obs to a .json(.gz) file
"""Export a list of Obs or structures containing Obs to a .json(.gz) file.
Dict keys that are not JSON-serializable such as floats are converted to strings.

Parameters
----------
Expand Down Expand Up @@ -565,7 +583,7 @@ def dict_replace_obs(d):
counter += 1
elif isinstance(v, str):
if bool(re.match(r'%s[0-9]+' % (reps), v)):
raise Exception('Dict contains string %s that matches the placeholder! %s Cannot be savely exported.' % (v, reps))
raise Exception('Dict contains string %s that matches the placeholder! %s Cannot be safely exported.' % (v, reps))
x[k] = v
return x

Expand All @@ -586,7 +604,7 @@ def list_replace_obs(li):
counter += 1
elif isinstance(e, str):
if bool(re.match(r'%s[0-9]+' % (reps), e)):
raise Exception('Dict contains string %s that matches the placeholder! %s Cannot be savely exported.' % (e, reps))
raise Exception('Dict contains string %s that matches the placeholder! %s Cannot be safely exported.' % (e, reps))
x.append(e)
return x

Expand Down
4 changes: 4 additions & 0 deletions tests/json_io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,10 @@ def list_check_obs(l1, l2):
with pytest.raises(Exception):
jsonio.dump_dict_to_json(od, fname, description=desc)

od = {1: 'test', False: 'True', None: 'None'}
jsonio.dump_dict_to_json(od, fname, description={np.int64(1): np.float64(2.444444)})
jsonio.dump_dict_to_json(od, fname, description=np.float32(2.444444))

os.remove(fname + '.json.gz')


Expand Down
0