On 04/17/2013 03:05 PM, Johann Hibschman wrote:
Miki Tebeka <miki.teb...@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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to