Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>Have a node.js app that is receiving JSON data strings that contain the literal NaN, like</p> </blockquote> <p>Then your NodeJS app <strong>isn't</strong> receiving <a href="http://json.org">JSON</a>, it's receiving text that's vaguely JSON-like. <code>NaN</code> is not a valid JSON token.</p> <p>Three options:</p> <h3>1. Get the source to correctly produce JSON</h3> <p>This is obviously the preferred course. The data is not JSON, that should be fixed, which would fix your problem.</p> <h3>2. Tolerate the <code>NaN</code> in a simple-minded way:</h3> <p>You could replace it with <code>null</code> before parsing it, e.g.:</p> <pre><code>var result = JSON.parse(yourString.replace(/\bNaN\b/g, "null")); </code></pre> <p>...and then handle <code>null</code>s in the result. But that's very simple-minded, it doesn't allow for the possibility that the characters <code>NaN</code> might appear in a string somewhere.</p> <p>Alternately, spinning Matt Ball's <code>reviver</code> idea <em>(now deleted)</em>, you could change it to a special string (like <code>"***NaN***"</code>) and then use a reviver to replace that with the real <code>NaN</code>:</p> <pre><code>var result = JSON.parse(yourString.replace(/\bNaN\b/g, '"***NaN***"'), function(key, value) { return value === "***NaN***" ? NaN : value; }); </code></pre> <p>...but that has the same issue of being a bit simple-minded, assuming the characters <code>NaN</code> never appear in an appropriate place.</p> <h3>3. Use <em>(shudder!)</em> <code>eval</code></h3> <p><em><strong>If you know and trust the source of this data and there's NO possibility of it being tampered with in transit</em></strong>, then you could use <code>eval</code> to parse it instead of <code>JSON.parse</code>. Since <code>eval</code> allows full JavaScript syntax, including <code>NaN</code>, that works. Hopefully I made the caveat bold enough for people to understand that I would only recommend this in a very, very, <em>very</em> tiny percentage of situations. But again, remember <code>eval</code> allows arbitrary execution of code, so if there's any possibility of the string having been tampered with, don't use it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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