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 }
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)
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?