Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
1  
day is undefined, you probably meant 'day' – Kevin B Nov 1 '12 at 4:23
up vote 4 down vote accepted

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/

share|improve this answer
    
thanks a lot. It helped – hello world Nov 1 '12 at 4:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.