Why is one number valid json?

1 is not a valid "JSON text", but most JSON parsers accept it anyway. Not all do, as you found with jsonlint.

I posted a more complete explanation with information from the JSON RFC along with Douglas Crockford's opinion in response to another question.


Although 1 isn't a valid JSON object, it is a valid JSON number. It seems that $.parseJSON parses all JSON values, not just objects.


parseJSON actually just returns the javascript object from a well formed json string. The json format accepts more than just (associative) arrays. It accepts data structures like:

  1. Objects
  2. Arrays
  3. Values
  4. Strings
  5. Numbers

Take a look at http://json.org/ for all the details concerning json.

$.parseJSON("1") actually reads a valid javascript number 1, resulting into 1


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