Skip to content

Instantly share code, notes, and snippets.

@kingspp
Last active September 12, 2021 00:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingspp/f2d8bac2f2efc4a01021367ef39f6396 to your computer and use it in GitHub Desktop.
Save kingspp/f2d8bac2f2efc4a01021367ef39f6396 to your computer and use it in GitHub Desktop.
Custom Json Encoder for json.dump()
# -*- 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