Cody Raspien Cody Raspien - 3 months ago 11
JSON Question

Parsing JSON - Javascript - Undefined

Here is my JSON:

[
{
"0": "324",
"1": "Cavill ",
"2": "11",
"3": "100018463",
"4": "RAR",
"5": "DummyX",
"6": "DummyY",
"7": "Moretext",
"8": "moretext",
"id": "lol",
"teacher": "Specsavers ",
"rate": "11",
"teacherid": "100018463",
"address": "114 Road X",
"postcode": "WXER 21",
"lat": "51.511871",
"lon": "-0.112934",
"distance": "0.023308985382378217"
}
]


This is held in a variable called "hold".

I am trying to output "teacher" in a div called output1.

Here is my code:

obj = JSON.parse(hold);
document.getElementById("output1").innerHTML = obj[1].teacher;


I keep getting undefined.

I tried changing 1 to 0. Same issue - undefined.

What am I doing wrong here?

How do I access attribute data from each node/branch?

Answer

Index starts from 0 and in your data index 1 is undefied.

obj = JSON.parse(hold);
document.getElementById("output1").innerHTML = obj[0].teacher;
//------------------------------------------------^^^------