$.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.
JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.
As for new JSON RFC, json, containing only single value is pretty valid. A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. For reasons of extensibility, one should always use an object, especially when dealing with a Rest API.
JSON NumbersNumbers in JSON must be an integer or a floating point.
In JSON, 6 is the number six. "6" is a string containing the digit 6 . So the answer to the question "Can json numbers be quoted?" is basically "no," because if you put them in quotes, they're not numbers anymore.
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.
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
If you have a look at the source of the jQuery method it will become clear very quickly.
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 );
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With