How to acces first array in JSON object?

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!

Answer

Your example doesn’t work because you’re not accessing an array but an object. You’d have to structure your JSON response like this:

'athletes' : [
    {
        'name': 'xyz',
        'year': 2021,
        ...
    },
    {
        'name': 'abc',
        'year': 2020,
        ...
    },
]

Now you can access the first array-item like response.athletes[0].name.