So I'm trying to create a page through using data from a json file with XMLHttprequest. But I can't seem to find how I acces the first array.
This is my data.json file with some testing values:
{
"athletes": {
"athlete": {
"name": "Example name",
"year": 2021,
"lift": {
"Deadlift": "180kg",
"Squat": "120kg",
"Benchpress": "100kg"
}
},
"athlete": {
"name": "Nice example name",
"year": 2020,
"lift": {
"Deadlift": "80kg",
"Squat": "100kg",
"Benchpress": "140kg"
}
}
}
}
Here is my script:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
document.getElementById("test-data").innerText = response.athletes.athlete.name;
}
};
xhttp.open("GET", "data.json", true);
xhttp.send();
Right now the HTML file shows in the div container: Nice example name. But I can't seem to get the Athlete array with the name Example name. I've tried a lot of possibilities like:
response.athletes[0].athlete.name
response.athletes.athlete[0].name
for (let i in response.athletes) {
document.getElementById("test-data").innerText = response.athletes[i].athlete.name;
}
But none of them have worked. Does anyone have an idea how to target the first athlete array in this code example? Thanks in advance!
athletekey on the same object/property level) the data is purely nested key-value pairs.athleteis the equivalent of a rewrite of the previous oneathleteskey is an object holding two identical keys, which isn't possible. I'm guessing this the athletes' object should be an array instead, containing the two athlete objects. Can you check this? Maybe try and log the response variable to see how your code views the data structure.