当前位置:   article > 正文

python null变成nan,Python JSON编码器将NaN改为'null'

python的nan如何替换成null

I'm writing code to receive an arbitrary object (possibly nested) capable of being converted to JSON.

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'?

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]}'

EXPECTED RESULT: '{"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]}'

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/719939
推荐阅读
相关标签
  

闽ICP备14008679号