She*_*zod 5 jquery parsing json
var x = {
"Item1" : 1,
"Item2" : {
"Item3" : 3
}
}
alert(JSON.stringify(x, undefined, 2));
alert($.parseJSON(x));
Run Code Online (Sandbox Code Playgroud)
第一个警告有效对象.第二个警告null.在实际代码中,"x"变量可以是字符串或对象,因此我应该能够解析这两种类型.我错过了什么吗?
你正在解析一个对象.你解析字符串,而不是对象; jQuery.parseJSON只需要字符串.从文档:
jQuery.parseJSON(json)
- JSON
- 要解析的JSON字符串.
用法:
if (! window.console) {
console = {
log: function (msg) {
alert(msg);
}
};
}
console.log($.parseJSON(JSON.stringify(x, undefined, 2)));
Run Code Online (Sandbox Code Playgroud)
标准jQuery似乎没有JSON字符串.通常,jQuery会为您处理,因此没有必要.如果你需要它,有各种插件.