Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to parse JSON string containing "NaN" in Node.js
    primarykey
    data
    text
    <p>Have a node.js app that is receiving JSON data strings that contain the literal NaN, like</p> <pre><code> "[1, 2, 3, NaN, 5, 6]" </code></pre> <p>This crashes <code>JSON.parse(...)</code> in Node.js. I'd like to parse it, if i can into an object.</p> <p>I know <code>NaN</code> is not part of JSON spec. Most SO links (<a href="https://stackoverflow.com/questions/6601812/sending-nan-in-json">sending NaN in json</a>) suggest to fix the output.</p> <p>Here, though the data is produced in a server I don't control, it's by a commercial Java library where I can see the source code. And it's produced by Google's Gson library:</p> <pre><code>private Gson gson = (new GsonBuilder().serializeSpecialFloatingPointValues().create()); ... gson.toJson(data[i], Vector.class, jsonOut) </code></pre> <p>So that seems like a legitimate source. And according to the <a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#serializeSpecialFloatingPointValues%28%29" rel="nofollow noreferrer">Gson API Javadoc</a> it says I should be able to parse it:</p> <blockquote> <p>Section 2.4 of JSON specification disallows special double values (NaN, Infinity, -Infinity). However, Javascript specification (see section 4.3.20, 4.3.22, 4.3.23) allows these values as valid Javascript values. Moreover, most JavaScript engines will accept these special values in JSON without problem. So, at a practical level, it makes sense to accept these values as valid JSON even though JSON specification disallows them.</p> </blockquote> <p>Despite that, this fails in both Node.js and Chrome: <code>JSON.parse('[1,2,3,NaN,"5"]')</code></p> <p><strong>Is there a flag to set in JSON.parse()? Or an alternative parser that accepts <code>NaN</code> as a literal?</strong></p> <p>I've been Googling for a while but can't seem to find a doc on this issue. </p> <p><a href="https://stackoverflow.com/questions/13581843/php-how-to-encode-infinity-or-nan-numbers-to-json/13582033#13582033">PHP: How to encode infinity or NaN numbers to JSON?</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload