123456789101112131415161718192021222324252627282930313233343536373839 |
- import json
- import math
- def replace_special_floats(obj):
- """
- 递归地替换字典和列表中的特殊浮点数(inf, -inf, nan)为字符串表示。
- """
- if isinstance(obj, dict):
- return {k: replace_special_floats(v) for k, v in obj.items()}
- elif isinstance(obj, list):
- return [replace_special_floats(item) for item in obj]
- elif isinstance(obj, float) and (math.isinf(obj) or math.isnan(obj)):
- if math.isinf(obj):
- return "Inf" if obj > 0 else "-Inf"
- else:
- return "NaN"
- else:
- return obj
- # 示例字典
- data = {
- "value1": float('inf'),
- "value2": -float('inf'),
- "value3": float('nan'),
- "nested": {
- "value4": float('inf')
- },
- "list": [float('inf'), float('nan')]
- }
- # 替换特殊浮点数
- clean_data = replace_special_floats(data)
- # 转换为JSON字符串
- json_str = json.dumps(clean_data, indent=4)
- print(json_str)
|