data.wrangling.json
Data - Wrangling - json¤
JSONEncoder (JSONEncoder)
¤
data serializer for json
default(self, obj)
¤
default serializer
Source code in dietbox/data/wrangling/json.py
def default(self, obj):
"""
default serializer
"""
if isinstance(obj, (datetime.datetime, datetime.date)):
return {"__type__": "__datetime__", "datetime": obj.isoformat()}
return json.JSONEncoder.default(self, obj)
NumpyEncoder (JSONEncoder)
¤
default(self, obj)
¤
Implement this method in a subclass such that it returns
a serializable object for o
, or calls the base implementation
(to raise a TypeError
).
For example, to support arbitrary iterators, you could implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
Source code in dietbox/data/wrangling/json.py
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
decode(obj)
¤
decode decodes the JSONEncoder results
Source code in dietbox/data/wrangling/json.py
def decode(obj):
"""
decode decodes the JSONEncoder results
"""
if "__type__" in obj:
if obj["__type__"] == "__datetime__":
return dateutil.parser.parse(obj["datetime"])
return obj
isoencode(obj)
¤
isoencode decodes many different objects such as np.bool -> regular bool
Source code in dietbox/data/wrangling/json.py
def isoencode(obj):
"""
isoencode decodes many different objects such as
np.bool -> regular bool
"""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
if isinstance(obj, datetime.date):
return obj.isoformat()
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.int64):
return int(obj)
if isinstance(obj, np.float64):
return float(obj)
if isinstance(obj, np.bool_):
return bool(obj)