如何在jQuery 1.9.1中使用$ .parseJSON? [英] how do you use $.parseJSON in jQuery 1.9.1?
问题描述
我正在使用此功能来测试JSON对象的有效性:
I'm using this function to test the validity of JSON objects:
function is_JSON( test ) {
try { var c = $.parseJSON( test );
} catch (e) { return false; }
return true;
}
您可以在这里看到它与jQuery 1.8.3一起使用的效果很好...
You can see it work great here, with jQuery 1.8.3 ...
...但是如果您切换到jQuery 1.9.1,则无法使用!
... but if you switch to jQuery 1.9.1, this doesn't work!
我想念什么?有没有更好的方法来测试有效的JSON?
What am I missing? Is there a better way to test for valid JSON?
推荐答案
这部分代码:
var test = ['thing1','thing2','thing3'];
创建一个数组,而不是包含有效JSON表达式的字符串.它似乎可以与1.8.3一起使用的原因是因为当时
Creates an array instead of a string containing a valid JSON expression. The reason why it seemed to work with 1.8.3 is because back then parseJSON
looked like this:
function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// ...
}
如您所见,如果将数组作为第一个参数传递,它将返回null
;它不会引发异常.
As you can see, if you pass an array as the first argument, it will return null
; it doesn't throw an exception.
您的函数然后返回true
:
parseJSON: function is_JSON( test ) {
try { var c = $.parseJSON( test );
} catch (e) { return false; }
// c === null
return true;
}
从1.9开始,这就是 parseJSON
看起来像:
Since 1.9, this is what parseJSON
looks like:
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( data === null ) {
return data;
}
// etc.
如果所传递的参数不是有效的JSON表达式,window.JSON.parse()
将引发异常.
And window.JSON.parse()
will throw an exception if the passed parameter is not a valid JSON expression.
有效的表达式是这样:
'["thing1","thing2","thing3"]'
要测试:
> JSON.parse('["thing1","thing2","thing3"]')
["thing1", "thing2", "thing3"]
这篇关于如何在jQuery 1.9.1中使用$ .parseJSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!