Struggling with iterating through the following return json string from an API:
{
"data": [
{
"ActionNeeded": null,
"OldestStatus": null,
"ServiceHost": "W501",
"ServiceName": "Renewals",
"ServiceStatusDateTime": "2023-03-15T22:47:05.313000",
"ServiceVersion": "1.0.0",
"SortOrder": "0",
"TimeAgo": null
},
{
"ActionNeeded": null,
"OldestStatus": null,
"ServiceHost": "W202",
"ServiceName": "Monitor",
"ServiceStatusDateTime": "2023-03-15T22:46:42.560000",
"ServiceVersion": null,
"SortOrder": "1",
"TimeAgo": null
},
{
"ActionNeeded": null,
"OldestStatus": null,
"ServiceHost": "W0070204",
"ServiceName": "Monitor",
"ServiceStatusDateTime": "2023-03-15T22:46:39.840000",
"ServiceVersion": "2.0.2",
"SortOrder": "1",
"TimeAgo": null
}
]
]
I’ve tried a for..in loop, but am only managing to get the first "set" of key/value pairs.
Here is my current code:
var json_obj = JSON.parse(event.data);
// Returned records
const items = json_obj['data'];
for (var item_index in items) {
if (items.hasOwnProperty(item_index)) {
console.log(item_index);
}
}
How can I loop through each "set" of data and out both key and value?
>Solution :
To loop through the nested JSON object provided, you can use JavaScript’s forEach loop. In this example, the JSON object has a property called data which contains an array of objects. You can loop through each object in the array and access its properties like this:
const jsonObject = {
"data": [
//... your JSON data
]
};
// Loop through the data array
jsonObject.data.forEach((item) => {
console.log('ActionNeeded:', item.ActionNeeded);
console.log('OldestStatus:', item.OldestStatus);
console.log('ServiceHost:', item.ServiceHost);
console.log('ServiceName:', item.ServiceName);
console.log('ServiceStatusDateTime:', item.ServiceStatusDateTime);
console.log('ServiceVersion:', item.ServiceVersion);
console.log('SortOrder:', item.SortOrder);
console.log('TimeAgo:', item.TimeAgo);
console.log('-------------------');
});
If you don’t know the property names in advance you can do like this:
for (const item of jsonObject.data) {
// Loop through the keys and values of the current item
for (const [key, value] of Object.entries(item)) {
console.log(`${key}: ${value}`);
}
console.log('-------------------');
}