Tengo una consulta https que devuelve un json blob en el siguiente formato:
{ "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 } } ] } ] }}
Quiero encontrar y extraer el valor de call_count . ¿Cuál es la mejor manera de hacer eso con Javascript? El siguiente código realmente imprimirá todos los valores json, incluido call_count , pero todos mis esfuerzos para obtener el valor de call_count están fallando.
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>");¡Cualquier comentario sería muy apreciado!
Sí, bueno, primero está el atributo metric_data que ha ignorado. Entonces, las métricas son una matriz de objetos. Su fragmento tiene un objeto, pero sigue siendo una matriz de objetos. Un objeto en esa matriz tiene intervalos de tiempo, que es una matriz de objetos.
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); console.log(obj.metric_data.metrics[0].timeslices[0].values.call_count);