user6690217 user6690217 - 3 months ago 9
JSON Question

Retrieve data from a local nested JSON objects

I made a little test page which looks something like this:

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<title>Get JSON Value</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

</head>
<body>

<script>

var json = $.getJSON("../js/report.json", function(data)
{
var items = [];

$.each(data, function (key, value)
{
items.push(key + " " + value);
});

alert(items[3]);
});

</script>

</body>
</html>


It fetches the data from a local JSON file stored on my local server.

The JSON object looks something like this:

{
"reportTitle": "Results",
"inlineAssets": false,
"stats": {
"suites": 7,
"tests": 13,
"passes": 11,
"pending": 0,
"failures": 2,
"start": "2016-08-11T13:30:48.362Z",
"end": "2016-08-11T13:31:29.433Z",
"duration": 41071,
...
}


alert(items[2]);
gives me
stats [object Object]

alert(items[3]);
gives me
suites [object Object]


Is it possible for me to retrieve the number of
suites
,
tests
and
passes
?
So the output of the alert would be
suites 7
,
tests 13
and
passes 11
.

EDIT:

Ideally I'd like to store these values in variables of their own instead of just
alert
or
console.log
.

EDIT for
david

enter image description here

EDIT 3:

I've tried:

console.log(items[2].suites);
=>
undefined

Answer

Here is a way to retrieve number of suites, tests, passes.

Retrieving number of suites => items[3].stats.suites

Retrieving number of tests => items[3].stats.tests

Retrieving number of passes => items[3].stats.passes

Replace 3 inside the brackets with whatever index number you want.


EDIT

You can forget my answer above. This is the real answer. I have modified your code a bit to get your desired answer.

var items=[];
function recursive(data){
    $.each(data, function (key, value)
    {
        if (value instanceof Object) {
            recursive(value);
        } else {
            items.push(key + " " + value);
        }
    });
}

var json = $.getJSON("report.json", function(data) 
{
    recursive(data);
    console.log(items[2]); // return 'suites 7'
    console.log(items[3]); // return 'tests 13'
    console.log(items[4]); // return 'passes 11'
});

Since there is an object inside an object, I have to use recursive to trace all the data.