Read data from arrays in javascript

I'm trying to read data from an array in JSON with javascript but I can't get it working. This is the segment of the JSON file from wich I want to read the data, I want to read the age variable from different arrays:

{
    "failCount" : 1,
    "skipCount" : 15,
    "totalCount" : 156,
    "childReports" : 
    [
        {
            "result" : 
            {
                duration : 0.97834,
                empty : false,
                suites : 
                [
                    cases : 
                    [
                        {
                            "age" : 0,
                            "status" : Passed
                        }
                        {
                            "age" : 15,
                            "status" : Passed
                        }
                        {
                            "age" : 3,
                            "status" : failed
                        }
                    ]
                ]
            }
        }
    ]
}

I've tried this:

for (var i = 0; i < jsonData.childReports.suites.cases.length; i++) 
{
    var age = jsonData.childReports.suites.cases[i];
}

But it doesn't work. What would be the best way to do this?

Thanks in advance, Matthijs.

Upvotes: 0

Views: 61

Answers (3)

cracker
cracker

Reputation: 4906

This way you can achieve that :

var data = {
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
    duration : 0.97834,
    empty : false,
        suites : [{
        cases : [
        {
        "age" : 0,
        "status" : "Passed"
        },
        {
        "age" : 15,
        "status" : "Passed"
        },
        {
        "age" : 3,
        "status" : "failed"
        }
    ]}
    ]
}
}]
};

 for (var i = 0; i < data.childReports[0].result.suites[0].cases.length; i++) {
        console.log(data.childReports[0].result.suites[0].cases[i].age);
    }

DEMO

Upvotes: 0

Bikee
Bikee

Reputation: 1197

Correct Json:

{
"failCount" : 1,
"skipCount" : 15,
"totalCount" : 156,
"childReports" : [
{
"result" : {
    duration : 0.97834,
    empty : false,
        suites : [{
        cases : [
        {
        "age" : 0,
        "status" : "Passed"
        },
        {
        "age" : 15,
        "status" : "Passed"
        },
        {
        "age" : 3,
        "status" : "failed"
        }
    ]}
    ]
}
}]
}

Upvotes: 0

harry
harry

Reputation: 448

Try the following code:

  for (var i = 0; i < jsonData.childReports[0].result.suites[0].cases.length; i++) {
        var age = jsonData.childReports[0].result.suites[0].cases[i].age;
    }

Upvotes: 1

Related Questions