-2

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?

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
The_HKT
  • 9
  • 1
  • may I edit your question to create a [StackSnippets](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) ? – Randy Casburn Nov 16 '21 at 16:02
  • why are you parsing it after you stringily it, you do it then undo it – Bobby Mannino Nov 16 '21 at 16:09
  • well my teacher told me in class that we have to stringily and then parse it to make a deep copy. it didnt make sense to me neither – The_HKT Nov 16 '21 at 16:13
  • "_my teacher told me_" - Using a "JSON.parse-then-stringify" approach is one technique for creating a deep copy of a JS object - if a deep copy is what you need. Side note: there are some [limitations](https://stackoverflow.com/a/122704/12567365) to that approach. – andrewJames Nov 16 '21 at 16:23

1 Answers1

4

Try parse only

json = JSON.parse(xhr.responseText);
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43