简体   繁体   中英

Iterating through JSON file

I am trying to read schedule data from a JSON file called js/schedule.json which looks like:

[
{"date":"12/06/2014","day":"Thursday","kick-off":"21:00","team1":"Brazil","team2":"Croatia","group":"A","stage":"group stages","broadcaster":"ITV"},
{"date":"13/06/2014","day":"Friday","kick-off":"17:00","team1":"Mexico","team2":"Cameroon","group":"A","stage":"group stages","broadcaster":"ITV"}

...    
]

I want to iterate through each item in the JSON object and only return the match fixture where the "date" matches a previously set variable called: today .

The jQuery I'm using is the following:

function getArray(){
    return $.getJSON('js/schedule.json');
}

getArray().done( function(json) {
    console.log(json); // show the json data in console
    var _len = json.length;
    var fixture;


    //loop through json and match today's date with match-date
    for (var i in json) {
        fixture = json[i];
        if (fixture.date == today) {
            //print out today's schedule here
            console.log(fixture.team1 + " Vs. " + fixture.team2);
        }
    }

});

However, what I get as an output in the Console is [Object, Object, Object, Object, Object, Object, Object] , there are 7 items in the object so this is the correct amount for the time being, however I can't get the console to show the fixture.team1 + fixture.team2

I've checked various posts which have similar problems such as JSON returning [object Object] but these don't quite fix it.

Any help would be fantastic. Cheers!

As pointed out the problem here was with the value of today not matching the value in the date . After adding a preceding "0" to months/days < 10 the code worked.

You're using for ... in when you want a normal for loop (given your data is an array of objects, not an object with a lot of unknown properties/keys). With that said, try something like:

getArray().done(function(json){
    // ...

    for (var i = 0; i < json.length; i++){
       var o = json[i]; // {"date":"12/06/2014","day":"Tursday",...}
       // now perform a check against `o['date']` or `o.date` and return the
       // matching result
    }
});

Output

[Object, Object, Object, Object, Object, Object, Object]

is an output of

console.log(json); // show the json data in console   

You have never got output of

console.log(fixture.team1 + " Vs. " + fixture.team2);

because your condition in if-condition is always false in your example. So, you should specify properly value for today variable.

If you want to log json object, you can use JSON.stringify function

console.log(JSON.stringify(json));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM