Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx05.eternal-september.org!.POSTED!not-for-mail From: Johann Hibschman Newsgroups: comp.lang.python Subject: Re: Encoding NaN in JSON Date: Wed, 17 Apr 2013 14:05:30 -0500 Organization: A noiseless patient Spider Lines: 27 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx05.eternal-september.org; posting-host="7dfe042e387f4fa00b031ca241f7a32a"; logging-data="7730"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18aNT3kfOimZp3AXjd+1mwYF93qn5ICfBw=" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.3 (windows-nt) Cancel-Lock: sha1:mkpg0w+egy+Da9v2Co12df+oeEg= sha1:comt2Dg3QdbgP6M0sRfgaWxK6jk= Xref: csiph.com comp.lang.python:43776 Miki Tebeka 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 Then just use json.dumps(transform(x)) rather than just json.dumps(x)