2

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.

1
  • 1
    day is undefined, you probably meant 'day' Commented Nov 1, 2012 at 4:23

1 Answer 1

4

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/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.