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

87 lines
2.8 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Utilities for dealing with writing json strings.
  16. json_utils wraps json.dump and json.dumps so that they can be used to safely
  17. control the precision of floats when writing to json strings or files.
  18. """
  19. import json
  20. from json import encoder
  21. def Dump(obj, fid, float_digits=-1, **params):
  22. """Wrapper of json.dump that allows specifying the float precision used.
  23. Args:
  24. obj: The object to dump.
  25. fid: The file id to write to.
  26. float_digits: The number of digits of precision when writing floats out.
  27. **params: Additional parameters to pass to json.dumps.
  28. """
  29. original_encoder = encoder.FLOAT_REPR
  30. if float_digits >= 0:
  31. encoder.FLOAT_REPR = lambda o: format(o, '.%df' % float_digits)
  32. try:
  33. json.dump(obj, fid, **params)
  34. finally:
  35. encoder.FLOAT_REPR = original_encoder
  36. def Dumps(obj, float_digits=-1, **params):
  37. """Wrapper of json.dumps that allows specifying the float precision used.
  38. Args:
  39. obj: The object to dump.
  40. float_digits: The number of digits of precision when writing floats out.
  41. **params: Additional parameters to pass to json.dumps.
  42. Returns:
  43. output: JSON string representation of obj.
  44. """
  45. original_encoder = encoder.FLOAT_REPR
  46. original_c_make_encoder = encoder.c_make_encoder
  47. if float_digits >= 0:
  48. encoder.FLOAT_REPR = lambda o: format(o, '.%df' % float_digits)
  49. encoder.c_make_encoder = None
  50. try:
  51. output = json.dumps(obj, **params)
  52. finally:
  53. encoder.FLOAT_REPR = original_encoder
  54. encoder.c_make_encoder = original_c_make_encoder
  55. return output
  56. def PrettyParams(**params):
  57. """Returns parameters for use with Dump and Dumps to output pretty json.
  58. Example usage:
  59. ```json_str = json_utils.Dumps(obj, **json_utils.PrettyParams())```
  60. ```json_str = json_utils.Dumps(
  61. obj, **json_utils.PrettyParams(allow_nans=False))```
  62. Args:
  63. **params: Additional params to pass to json.dump or json.dumps.
  64. Returns:
  65. params: Parameters that are compatible with json_utils.Dump and
  66. json_utils.Dumps.
  67. """
  68. params['float_digits'] = 4
  69. params['sort_keys'] = True
  70. params['indent'] = 2
  71. params['separators'] = (',', ': ')
  72. return params