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 extract 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, for 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 159, so it counts every single character as an element.

EDIT: When I upgrade to:

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

I get length 1 (this is correct), but 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) 
+6
source share
1 answer

You substitute json string already:

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

it should be:

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

If you are JSON.stringify("foo") , then you get a line with quotes: "\"foo\"" .

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

  • Properties of objects other than an array are not guaranteed in any particular order. Do not rely on ordering the properties inside the same object inside the gating.
  • Boolean , Number and String Objects are converted to the corresponding primitive values ​​during stringing, in accordance with the traditional conversion of semantics.
  • If undefined, a function or symbol occurs during the conversion, either omitted (when it is in the object) or censored to null (when it is found in the array). JSON.stringify can also just return undefined when passing "clean" values, such as JSON.stringify (function () {}) or JSON.stringify (undefined).
  • All properties with symbol keys will be completely ignored, even when using the replace function.
  • Invalid 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

+8
source

Source: https://habr.com/ru/post/1015794/


All Articles