gpt4 book ai didi

jquery - $.parseJSON() 在有效对象上返回 null

转载 作者:行者123 更新时间:2023-12-03 22:58:53 25 4
gpt4 key购买 nike

jsfiddle link

var x = {
"Item1" : 1,
"Item2" : {
"Item3" : 3
}
}

alert(JSON.stringify(x, undefined, 2));
alert($.parseJSON(x));

第一个警报有效对象。第二个警报为空。在实际代码中,“x”变量可以是字符串或对象,因此我应该能够解析这两种类型。我错过了什么吗?

最佳答案

您正在解析一个对象。您解析字符串,而不是对象; jQuery.parseJSON只需要字符串。来自文档:

jQuery.parseJSON( json )
json
The JSON string to parse.

用法:

if (! window.console) {
console = {
log: function (msg) {
alert(msg);
}
};
}

console.log($.parseJSON(JSON.stringify(x, undefined, 2)));

标准 jQuery 似乎没有 JSON 字符串生成器。通常,jQuery 会为您处理该问题,因此没有必要。如果您需要它,有各种插件。

关于jquery - $.parseJSON() 在有效对象上返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com