简体   繁体   中英

Javascript: Trying to access elements of a JSON array gives me individual characters

$.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));
    }
});

Then, in another file I am retrieving the JSON from sessionStorage:

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

This gives me an array of JSON objects, example: [{'name':'Bob',...}] . However, when I try to access the first element of the array: json[0] , I get '[' and when I try json[0].name I get undefined . The length of json is reported as 159, so it is counting each individual character as an element.

EDIT: When I update to:

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

I get a length of 1 (which is correct), but an error when accessing 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)

You are stringifying the already stringified json:

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

this should be:

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

If you JSON.stringify("foo") , then you got a quoted string: "\\"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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM