jqueryjsonparsing

Why is one number valid json?


$.parseJSON("1") returns 1. I would expect this to throw an error because this does not seem like valid JSON of the form:

{
    "firstName": "John"
}

Why does 1 parse correctly? Is there anyway to get this to throw an error instead.


Solution

  • Parsing a number

    You can better handle the parsing of numbers using parseInt(). It will return a number on success and NaN (Not a Number) otherwise.

    var a = parseInt('23');
    isNan(a); // false
    
    var b = parseInt('ab');
    isNan(b); // true
    

    Why it returns 1 in jQuery

    If you have a look at the source of the jQuery method it will become clear very quickly.

    1. It will check if there is native support for JSON.parse.
    2. If not, it will create an anonymous function (with string body) that simply returns the data contained in the JSON string and calls it.

    So if in your case step 2. is executed it will simply return 1 even though it's not real JSON.

    UPDATE: I was curious how the native JSON.parse would handle it and it does the same thing (returning 1). So regardless of the implementation you always get the same result.

    Library on display: http://code.jquery.com/jquery-1.8.3.js

    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 && 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 );
    },