简体   繁体   中英

Parsing external JSON file(containing array elements) in Javascript using JQuery

I would like to parse the external JSON file in javascript which has an array in it and other elements. Here is the JSON file named 'TotalUsers.json'

{"@version":"1.0",
"@generatedDate":"12/20/10 5:24 PM",
"day":[{"@value":"53819","@date":"2010-12-01"},
    {"@value":"57558","@date":"2010-12-02"},
    {"@value":"61141","@date":"2010-12-03"}]}

I would like to get the 'value' and 'day' elements of day array in two separate arrays daysTotal and valuesTotal. I am trying to achieve this using JQuery's getJSON method. However, I am confused with the internal formatting of day array.

After formatting this how the two output arrays should look like:

valuesTotal = [53819, 57558, 61141]; daysTotal = [2010-12-01, 2010-12-02, 2010-12-03];

This is I am upto sofar,

$.getJSON('TotalUsers.json', function(data) {
    var valuesTotal  = [];
    var daysTotal = [];
    $.each(data, function(key, val) {
        if (key == day)
        {
            daysTotal.push('<li id="' + key.key + '">' + key.val + '</li>');
        }
        else
        {
            valuesTotal .push('<li id="' + key + '">' + val + '</li>');
        }
    });
});

Please help me with the logic, I am pretty new to JSON and javascript.

Any help will be highly appreciated.

Thanks.

day is undefined, you probably meant 'day' , though what you really want is:

$.getJSON('TotalUsers.json', function(data) {
    var valuesTotal = [];
    var daysTotal = [];
    $.each(data.day, function(key, obj) {
        valuesTotal.push('<li id="value-' + key + '">' + obj["@value"] + '</li>');
        daysTotal.push('<li id="day-' + key + '">' + obj["@date"] + '</li>');
    });
});​

Just iterate over the day array, populating your two child arrays.

Demo: http://jsfiddle.net/hjjTU/

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