python null变成nan,Python JSON编码器将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]}'

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值