gpt4 book ai didi

Python JSON 编码器将 NaN 转换为 null

转载 作者:IT老高 更新时间:2023-10-28 20:40:16 31 4
gpt4 key购买 nike

我正在编写代码来接收能够转换为 JSON 的任意对象(可能是嵌套的)。

Python 内置 JSON 编码器的默认行为是将 NaN 转换为 NaN,例如json.dumps(np.NaN) 结果为 NaN。如何将此 NaN 值更改为 null

我试过 subclass JSONEncoder and override the default() method如下:

from json import JSONEncoder, dumps
import numpy as np

class NanConverter(JSONEncoder):
def default(self, obj):
try:
_ = iter(obj)
except TypeError:
if isinstance(obj, float) and np.isnan(obj):
return "null"
return JSONEncoder.default(self, obj)

>>> d = {'a': 1, 'b': 2, 'c': 3, 'e': np.nan, 'f': [1, np.nan, 3]}
>>> dumps(d, cls=NanConverter)
'{"a": 1, "c": 3, "b": 2, "e": NaN, "f": [1, NaN, 3]}'

预期结果:'{"a": 1, "c": 3, "b": 2, "e": null, "f": [1, null, 3]}'

最佳答案

这似乎达到了我的目的:

import simplejson


>>> simplejson.dumps(d, ignore_nan=True)
Out[3]: '{"a": 1, "c": 3, "b": 2, "e": null, "f": [1, null, 3]}'

关于Python JSON 编码器将 NaN 转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28639953/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com