Encoding NaN in JSON

Roland Koebler r.koebler at yahoo.de
Wed Apr 17 21:39:38 EDT 2013


Hi,

> > yes, there is: subclass+extend the JSON-encoder, see pydoc json.
> Please read the original post before answering. What you suggested does not work since NaN is of float type.
ok, right, default does not work this way.
But I would still suggest to extend the JSON-encoder, since that is
quite simple (see sourcecode of JSON module); as a quickhack, you
could even monkey patch json.encoder.floatstr with a wrapper which
returns "N/A" for NaN. (I've tested it: It works.)

But: If you only need NaN and inf, and are ok with 'NaN' instead of 'N/A',
you can simply use the json module. See pydoc json:

    If allow_nan is True, then NaN, Infinity, and -Infinity will be
    encoded as such.  This behavior is not JSON specification compliant,
    but is consistent with most JavaScript based encoders and decoders.
    Otherwise, it will be a ValueError to encode such floats.

>>> import json
>>> json.dumps(float('NaN'))
'NaN'
>>> json.dumps(float('inf'))
'Infinity'


Roland



More information about the Python-list mailing list