Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 335
lillemap Avatar asked Mar 16 '17 13:03

lillemap


1 Answers

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

like image 103
n00dl3 Avatar answered Oct 22 '22 06:10

n00dl3