Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>Parsing a number</h2> <p>You can better handle the parsing of numbers using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt"><code>parseInt()</code></a>. It will return a number on success and <code>NaN</code> (Not a Number) otherwise. </p> <pre><code>var a = parseInt('23'); isNan(a); // false var b = parseInt('ab'); isNan(b); // true </code></pre> <h2>Why it returns 1 in jQuery</h2> <p>If you have a look at the source of the jQuery method it will become clear very quickly.</p> <ol> <li>It will check if there is native support for JSON.parse.</li> <li>If not, it will create an anonymous function (with string body) that simply returns the data contained in the JSON string and calls it.</li> </ol> <p>So if in your case step <code>2.</code> is executed it will simply return <code>1</code> even though it's not real JSON.</p> <p><strong>UPDATE:</strong> I was curious how the native <code>JSON.parse</code> <a href="http://jsfiddle.net/bTmgw/">would handle it</a> and it does the same thing (returning <code>1</code>). So regardless of the implementation you always get the same result.</p> <p>Library on display: <a href="http://code.jquery.com/jquery-1.8.3.js">http://code.jquery.com/jquery-1.8.3.js</a></p> <pre><code>parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON &amp;&amp; window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); // Just returns JSON data. } jQuery.error( "Invalid JSON: " + data ); }, </code></pre>
 

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