You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

json.py 1.0 kB

1234567891011121314151617181920212223242526272829303132333435
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  2. import json
  3. import numpy as np
  4. from .base import FormatHandler
  5. def set_default(obj):
  6. """Set default json values for non-serializable values.
  7. It helps convert ``set``, ``range`` and ``np.ndarray`` data types to list.
  8. It also converts ``np.generic`` (including ``np.int32``, ``np.float32``,
  9. etc.) into plain numbers of plain python built-in types.
  10. """
  11. if isinstance(obj, (set, range)):
  12. return list(obj)
  13. elif isinstance(obj, np.ndarray):
  14. return obj.tolist()
  15. elif isinstance(obj, np.generic):
  16. return obj.item()
  17. raise TypeError(f'{type(obj)} is unsupported for json dump')
  18. class JsonHandler(FormatHandler):
  19. def load(self, file):
  20. return json.load(file)
  21. def dump(self, obj, file, **kwargs):
  22. kwargs.setdefault('default', set_default)
  23. json.dump(obj, file, **kwargs)
  24. def dumps(self, obj, **kwargs):
  25. kwargs.setdefault('default', set_default)
  26. return json.dumps(obj, **kwargs)

致力于通过开放的社区合作,开源AI模型以及相关创新技术,推动基于模型即服务的生态繁荣发展