本文介绍了Python JSON编码器改为将NaN转换为'null'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写代码以接收能够转换为JSON的任意对象(可能是嵌套的).
I'm writing code to receive an arbitrary object (possibly nested) capable of being converted to JSON.
Python内置JSON编码器的默认行为是将NaN转换为NaN
,例如json.dumps(np.NaN)
产生NaN
.如何将此NaN
值更改为'null'
?
The default behavior for Python's builtin JSON encoder is to convert NaNs to NaN
, e.g. json.dumps(np.NaN)
results in NaN
. How can I change this NaN
value to 'null'
?
我尝试子类JSONEncoder
并覆盖了default()
方法如下:
I tried to subclass JSONEncoder
and override the default()
method as follows:
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]}'
推荐答案
这似乎实现了我的目标:
This seems to achieve my objective:
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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!