为什么一个数字是有效的json? [英] Why is one number valid json?
问题描述
$.parseJSON("1")
返回1
.我希望这会引发错误,因为这看起来不像形式的有效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"
}
为什么1
可以正确解析?反正有办法让它抛出错误.
Why does 1
parse correctly? Is there anyway to get this to throw an error instead.
推荐答案
解析数字
您可以使用 parseInt()
.如果成功,它将返回一个数字,否则返回NaN
(不是数字).
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
为什么它在jQuery中返回1
如果您查看jQuery方法的源代码,它将很快变得很清楚.
Why it returns 1 in jQuery
If you have a look at the source of the jQuery method it will become clear very quickly.
- 它将检查是否存在对JSON.parse的本机支持.
- 否则,它将创建一个匿名函数(具有字符串主体),该函数仅返回JSON字符串中包含的数据并对其进行调用.
因此,如果您执行的是步骤2.
,即使它不是真正的JSON,它也会简单地返回1
.
So if in your case step 2.
is executed it will simply return 1
even though it's not real JSON.
更新:
我很好奇原生的JSON.parse
将如何处理,它会做同样的事情(返回1
).因此,无论采用哪种实施方式,您始终可以获得相同的结果.
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.
展出的图书馆: 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 );
},
这篇关于为什么一个数字是有效的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!