gpt4 book ai didi

Javascript:尝试访问 JSON 数组的元素会给我单独的字符

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:42 25 4
gpt4 key购买 nike

$.ajax({
url: "get_cards.php",
type: "GET",
data: {selection:JSON.stringify(selection)},
success: function(data) {
var json = JSON.parse(data);
sessionStorage.setItem("json", JSON.stringify(json));
}
});

然后,在另一个文件中,我从 sessionStorage 中检索 JSON:

var json = JSON.parse(JSON.stringify(sessionStorage.getItem("json")));
if(json) {
sessionStorage.removeItem("json");
}

这为我提供了一个 JSON 对象数组,例如:[{'name':'Bob',...}]。但是,当我尝试访问数组的第一个元素时:json[0],我得到了 '[' 并且当我尝试访问 json[0] 时。 name 我得到 undefinedjson 的长度报告为 159,因此它将每个单独的字符计为一个元素。

编辑:当我更新到:

var json = JSON.parse(sessionStorage.getItem("json"));
if(json) {
sessionStorage.removeItem("json");
}

我得到的长度为 1(这是正确的),但是在访问 json[0].name 时出错:

Uncaught TypeError: Cannot read property '0' of null
at HTMLDocument.<anonymous> (studying.js:10)
at j (jquery.min.js:2)
at k (jquery.min.js:2)

最佳答案

您正在对已经字符串化的 json 进行字符串化:

var json = JSON.parse(JSON.stringify(sessionStorage.getItem("json"))); // wrong !

这应该是:

var json = JSON.parse(sessionStorage.getItem("json"));

如果您JSON.stringify("foo"),那么您会得到一个带引号的字符串:"\"foo\""

JSON.stringify() converts a value to JSON notation representing it:

  • Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification.
  • Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.
  • If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array). JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).
  • All symbol-keyed properties will be completely ignored, even when using the replacer function.
  • Non-enumerable properties will be ignored

examples :

 JSON.stringify({});                  // '{}'
JSON.stringify(true); // 'true'
JSON.stringify('foo'); // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'

Source: MDN

关于Javascript:尝试访问 JSON 数组的元素会给我单独的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42835980/

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