Encoding NaN in JSON
Dave Angel
d at davea.name
Wed Apr 17 17:37:40 EDT 2013
On 04/17/2013 03:05 PM, Johann Hibschman wrote:
> Miki Tebeka <miki.tebeka at gmail.com> writes:
>
>>>> I'm trying to find a way to have json emit float('NaN') as 'N/A'.
>>> No. There is no way to represent NaN in JSON. It's simply not part of the
>>> specification.
>> I know that. I'm trying to emit the *string* 'N/A' for every NaN.
>
> Easiest way is probably to transform your object before you try to write
> it, e.g.
>
> def transform(x):
> if isinstance(x, dict):
> return dict((k, transform(v)) for k, v in x.items())
> elif isinstance(x, list) or isinstance(x, tuple):
> return [transform(v) for v in x]
> elif isinstance(x, float) and x != x:
> return 'N/A'
> else:
> return x
>
Note that for a self-referencing object, this function might run
"forever," or until it runs out of stack. The programmer is likely to
know about the possibility, but just in case ...
> Then just use
>
> json.dumps(transform(x))
>
> rather than just
>
> json.dumps(x)
>
--
DaveA
More information about the Python-list
mailing list