Last active
September 12, 2021 00:29
-
-
Save kingspp/f2d8bac2f2efc4a01021367ef39f6396 to your computer and use it in GitHub Desktop.
Custom Json Encoder for json.dump()
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
# -*- coding: utf-8 -*- | |
""" | |
| **@created on:** 18/07/18, | |
| **@author:** prathyushsp, | |
| **@version:** v0.0.1 | |
| | |
| **Description:** | |
| | |
| | |
| **Sphinx Documentation Status:** -- | |
| | |
""" | |
__all__ = ['JsonEncoder'] | |
import json | |
import tensorflow as tf | |
import numpy as np | |
import enum | |
import logging | |
logger = logging.getLogger(__name__) | |
class JsonEncoder(json.JSONEncoder): | |
""" Special json encoder for numpy types """ | |
def default(self, obj): | |
if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, | |
np.int16, np.int32, np.int64, np.uint8, | |
np.uint16, np.uint32, np.uint64)): | |
return int(obj) | |
elif isinstance(obj, (np.float_, np.float16, np.float32, | |
np.float64)): | |
return float(obj) | |
elif isinstance(obj, (np.ndarray,)): | |
return obj.tolist() | |
elif isinstance(obj, set): | |
return list(obj) | |
elif isinstance(obj, enum.Enum): | |
return obj.name | |
elif isinstance(obj, (tf.DType,tf.Tensor, tf.Variable, tf.Operation)): | |
return obj.name | |
else: | |
try: | |
return obj.default() | |
except Exception: | |
logger.error(f'{obj} is not serializable. ') | |
return f'Object not serializable - {obj}' | |
# Usage | |
import json | |
json.dump(obj, f, cls=JsonEncoder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment