Home > front end >  Accessing JSON with JavaScript
Accessing JSON with JavaScript

Time:11-17

So I got the following JSON that I get from doing a HTML Request:

{ "cities": [ { "plz": "91443", "name": "Scheinfeld" }, { "plz": "91448", "name": "Emskirchen" } ] }

I am saving this JSON in the following variable:

json = JSON.parse( JSON.stringify(xhr.responseText));
console.log(json.cities[0].plz);

However I get the following error message:

"Uncaught TypeError: Cannot read properties of undefined (reading '0') at XMLHttpRequest.xhr.onreadystatechange"

So it seems like trying to access plz with json.cities[0].plz is not the correct way. So how do I do it right?

CodePudding user response:

Try parse only

json = JSON.parse(xhr.responseText);
  • Related