Skip to content

Commit 3e39a44

Browse files
authored
Merge pull request #16 from Roman-Supernova-PIT/u/rknop/snpitjsonencoder
Add SNPITJsonEncoder to utils.py
2 parents 82203ff + 49752c5 commit 3e39a44

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

changes/16.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add SNPITJsonEncoder to utils.py

snpit_utils/utils.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
import os
44
import numbers
5+
import datetime
6+
import json
7+
import uuid
58
import collections.abc
9+
610
import numpy as np
711

812

@@ -57,3 +61,27 @@ def parse_bool(text):
5761
def env_as_bool( varname ):
5862
"""Parse an environment variable as a boolean."""
5963
return parse_bool( os.getenv(varname) )
64+
65+
66+
class SNPITJsonEncoder( json.JSONEncoder ):
67+
"""Some specific encodings we need for the JSON use.
68+
69+
We want to know how to encode UUIDs to strings.
70+
71+
We want to be able to encoded numpy stuff.
72+
73+
Encode datetime to isoformat strings.
74+
75+
"""
76+
77+
def default( self, obj ):
78+
if isinstance( obj, uuid.UUID ):
79+
return str
80+
if isinstance( obj, np.floating ):
81+
return float( obj )
82+
if isinstance( obj, np.bool_ ):
83+
return bool( obj )
84+
if isinstance( obj, np.ndarray ):
85+
return obj.tolist()
86+
if isinstance(obj, datetime ):
87+
return obj.isoformat()

0 commit comments

Comments
 (0)