I have an https query which returns a json blob in the following format:
{
"metric_data": {
"from": "2021-12-09T01:25:32+00:00",
"to": "2021-12-09T01:55:32+00:00",
"metrics_not_found": [],
"metrics_found": [
"Mobile/Crash/All"
],
"metrics": [
{
"name": "Mobile/Crash/All",
"timeslices": [
{
"from": "2021-12-09T01:24:00+00:00",
"to": "2021-12-09T01:54:00+00:00",
"values": {
"call_count": 5
}
}
]
}
]
}
}
I want to find and extract the value for call_count
. What is the best way to do that with Javascript? The following code will actually print out all the json values, including the call_count
but all my efforts to just grab the value for call_count
are failing.
var json = `{
"metric_data": {
"from": "2021-12-09T01:25:32+00:00",
"to": "2021-12-09T01:55:32+00:00",
"metrics_not_found": [],
"metrics_found": [
"Mobile/Crash/All"
],
"metrics": [
{
"name": "Mobile/Crash/All",
"timeslices": [
{
"from": "2021-12-09T01:24:00+00:00",
"to": "2021-12-09T01:54:00+00:00",
"values": {
"call_count": 5
}
}
]
}
]
}
}`;
// Convert a JSON object to a Javascript object
var obj = JSON.parse(json);
// This function prints nested values
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
// Printing all the values from the resulting object
printValues(obj);
document.write("<hr>");
// This is where I fail as I try to print a single value.
document.write(obj["metrics"]["call_count"] + "<br>");
Any feedback would be much appreciated!