You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python移除JSON文件中的NaN值(保留null)

Python移除JSON对象中值为NaN的键值对

针对你需要处理多JSON对象文件、删除值为NaN的键值对(保留null)的需求,以下是直接可行的Python实现方案:

核心思路

  1. 解析文件中的每个独立JSON对象(因文件非标准JSON数组,需逐个解析)
  2. 过滤掉值为NaN的键值对,保留null(对应Python中的None)
  3. 将处理后的对象写入新文件

完整代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 19:42:53