如何使用Python移除JSON文件中的NaN值(保留null)
Python移除JSON对象中值为NaN的键值对
针对你需要处理多JSON对象文件、删除值为NaN的键值对(保留null)的需求,以下是直接可行的Python实现方案:
核心思路
- 解析文件中的每个独立JSON对象(因文件非标准JSON数组,需逐个解析)
- 过滤掉值为
NaN的键值对,保留null(对应Python中的None) - 将处理后的对象写入新文件
完整代码
import json import math def clean_nan_entries(data): cleaned_dict = {} for key, value in data.items(): # 仅跳过值为NaN的键,保留null和其他正常值 if value is not None and isinstance(value, (int, float)) and math.isnan(value): continue cleaned_dict[key] = value return cleaned_dict # 替换为你的输入输出文件路径 input_path = "input.json" output_path = "output.json" with open(input_path, "r", encoding="utf-8") as infile, open(output_path, "w", encoding="utf-8") as outfile: decoder = json.JSONDecoder(parse_constant=lambda c: float('nan') if c == 'NaN' else c) content = infile.read() current_pos = 0 content_length = len(content) while current_pos < content_length: try: # 逐个解析JSON对象 obj, current_pos = decoder.raw_decode(content, current_pos) cleaned_obj = clean_nan_entries(obj) # 写入格式化后的JSON json.dump(cleaned_obj, outfile, indent=2) outfile.write("\n") except json.JSONDecodeError: # 跳过无效字符(如换行、空格) current_pos += 1
代码说明
clean_nan_entries函数:遍历字典键值对,通过math.isnan()判断数值类型的NaN,直接跳过对应键值对,保留null和其他有效值- 使用
json.JSONDecoder.raw_decode:解决多独立JSON对象无法直接用json.load读取的问题,逐个解析文件中的对象 parse_constant参数:将JSON中的NaN解析为Python可识别的float('nan'),确保判断逻辑有效
测试结果
针对你提供的输入示例,运行代码后输出文件内容如下:
{ "name": "John Doe", "age": 30, "height": null } { "name": "Jim Hanks" }
内容的提问来源于stack exchange,提问作者lhamo
相关产品推荐
相关产品推荐

