abnormal_json.py 946 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import json
  2. import math
  3. def replace_special_floats(obj):
  4. """
  5. 递归地替换字典和列表中的特殊浮点数(inf, -inf, nan)为字符串表示。
  6. """
  7. if isinstance(obj, dict):
  8. return {k: replace_special_floats(v) for k, v in obj.items()}
  9. elif isinstance(obj, list):
  10. return [replace_special_floats(item) for item in obj]
  11. elif isinstance(obj, float) and (math.isinf(obj) or math.isnan(obj)):
  12. if math.isinf(obj):
  13. return "Inf" if obj > 0 else "-Inf"
  14. else:
  15. return "NaN"
  16. else:
  17. return obj
  18. # 示例字典
  19. data = {
  20. "value1": float('inf'),
  21. "value2": -float('inf'),
  22. "value3": float('nan'),
  23. "nested": {
  24. "value4": float('inf')
  25. },
  26. "list": [float('inf'), float('nan')]
  27. }
  28. # 替换特殊浮点数
  29. clean_data = replace_special_floats(data)
  30. # 转换为JSON字符串
  31. json_str = json.dumps(clean_data, indent=4)
  32. print(json_str)