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

如何在simplejson.load()中将JSON null转换为nan?

解决simplejson.load将JSON null转为NaN的问题

嘿,这个需求我之前也碰到过,其实simplejson已经给我们准备好了对应的解决方案,不用自己从头写复杂的解析逻辑!

你知道用simplejson.dump(ignore_nan=True)能把Python里的NaN转成JSON的null,那反向操作的话,只需要在simplejson.load()(或者loads())里用parse_constant参数来定制null的解析行为就行。

具体怎么做呢?你可以定义一个小函数,让它在解析到JSON的null常量时返回math.nan,其他的JSON常量(比如Infinity、-Infinity)就按默认逻辑处理。直接看代码示例更清楚:

import simplejson as json
import math

def convert_null_to_nan(constant):
    # 当解析到JSON的null时,返回nan
    if constant == 'null':
        return math.nan
    # 其他常量(比如正负无穷)按默认方式解析
    return json.loads(constant)

# 测试用的JSON字符串
test_json = '{"temperature": null, "humidity": 65}'

# 默认情况:null会被解析成None
default_parse = json.loads(test_json)
print(default_parse)  # 输出: {'temperature': None, 'humidity': 65}

# 自定义解析:null转为NaN
custom_parse = json.loads(test_json, parse_constant=convert_null_to_nan)
print(custom_parse)  # 输出: {'temperature': nan, 'humidity': 65}

如果你的场景里不需要处理无穷大这类特殊值,还可以把这个函数简化得更短:

def convert_null_to_nan(constant):
    return math.nan if constant == 'null' else json.loads(constant)

这样就完美实现了你要的反向转换,和dump时的ignore_nan=True刚好形成对应,用起来特别顺手。

内容的提问来源于stack exchange,提问作者djmac

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:41:42