I'm having trouble extracting specific data from a JSON response. Here is an example of the response structure:
{
"status": "success",
"reservations": [
{
"id": "22959",
"subject": "SubjectName1",
"modifiedDate": "2017-04-03T06:04:24",
"startDate": "2017-04-03T12:15:00",
"endDate": "2017-04-03T17:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName1",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName1",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode1",
"name": "groupName1"
}
],
"description": ""
},
{
"id": "22960",
"subject": "SubjectName2",
"modifiedDate": "2017-04-04T06:04:33",
"startDate": "2017-04-04T10:00:00",
"endDate": "2017-04-04T16:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName2",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName2",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode2",
"name": "groupName2"
}
],
"description": ""
}
]
}
My attempts to extract this information using JSON.parse() and for-loops have been unsuccessful. I specifically need to retrieve the subject names, room names, building names, and student group names.
This is how my current code looks:
var getData = {
"startDate":,
"endDate":,
"studentGroup": [
""]
};
var data = new XMLHttpRequest();
data.onreadystatechange = function () {
if (data.readyState == 4 && data.status == 200) {
try {
// Parse JSON
var json = JSON.parse(data.responseText);
// for-loops
for (var i = 0; i < json.reservations.length; i++) {
for (var x = 0; x < json.reservations[i].length;
x++) {
document.getElementById("test").innerHTML =
json.reservations[i].subject;
}
}
} catch (err) {
console.log(err.message);
return;
}
}
};
// JSON query
data.open("POST", "URL", true, "APIKEY", "PASS");
data.setRequestHeader('Content-Type', 'application/json');
data.send(JSON.stringify(getData));
Currently, this code only displays the last subject name when there are more than one. How can I adjust it to get all the required data?