Python Json小写南 [英] Python Json lower case nan

查看:80
本文介绍了Python Json小写南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中解析一些json,并且正在使用NaN.不幸的是,我的资料写的NaN如下:

I'm trying to parse some json in python, and I'm making use of NaN. Unfortunately, my source writes NaN as follows:

{ "foo": nan }

这实际上并不罕见;在python中,它执行float('nan')来获得NaN,而C ++从NaN的double值中输出nan.不幸的是,我似乎无法弄清楚如何使python对此进行解析.我将其放在名为bar.txt的文件中,并尝试了以下操作:

This actually isn't so uncommon; in python one does float('nan') to get an NaN, and C++ outputs nan from an NaN double value. Unfortunately, I can't seem to figure out how to make python parse this. I put this in a file called bar.txt and tried the following:

def foo(s):
    print "hello"
    if s == 'nan' or s == 'NaN':
        return float('nan')
    else:
        return float(s)

def bar(s):
    print "blah"    

with open("bar.txt") as f:
    x = json.load(f, parse_float=foo, parse_constant=bar)

我得到一些回溯,其后是:ValueError: No JSON object could be decoded.打招呼或等等都不会被打印出来,这向我表明,实际上没有调用我的回调来处理这种情况.

I get some backtrace followed by: ValueError: No JSON object could be decoded. Neither hello nor blah get printed, which indicates to me that neither of my callbacks are actually being called to deal with this case.

有什么办法可以很好地做到这一点的吗?

Is there any way to do this nicely?

推荐答案

有什么办法可以很好地做到这一点的吗?

Is there any way to do this nicely?

否,无法仅使用已记录的json界面执行此操作.如果检查json/scanner.py,可以看到字符串NaN被硬编码到词法分析中,并且不能被替换.

No, there is no way to do this using only the documented json interface. If you examine json/scanner.py, you can see that the string NaN is hardcoded into the lexical analysis and cannot be replaced.

根据数据的确切性质,您也许可以使用正则表达式来解决问题.

Depending upon the precise nature of your data, you may be able to use a regular expression to solve your problem.

import json
import re

j = '{"Number": nan}'
j = re.sub(r'\bnan\b', 'NaN', j)

print json.loads(j)

这篇关于Python Json小写南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆