Search code examples
jqueryajaxjsongetjson

Accessing json objects with no name


I'm struggling to access this json code below. Every json value I've previously seen is something like this:

 var hold = { name: 'alex', job: 'realtor'}

So to access the name I would do something like hold.name. But my json data looks like this

[
    [
        {
            "count": "80",
            "countTxt":"Buyer logins",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"523"
        },
        {
            "count": "233",
            "countTxt":"Searches",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"628"
        },
        {
            "count": "533",
            "countTxt":"Views of our member pages",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"2,365"
        }
    ],
    [
        {
            "count": "80",
            "countTxt":"Total vists",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"412"
        },
        {
            "count": "53",
            "countTxt":"Unique visitors",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"731"
        },
        {
            "count": "1:12 min",
            "countTxt":"Total time spent on page",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"784.2 mins"
        }
    ]
]

The data is nested and it has no name so I don't know how to access. I know the question seems somewhat rudimental but I haven't seen any examples parse code that looks like this. It's always a more simple example like the one above. My .getjson code looks like this ...

var requestURL = 'assets/js/stats.json';
$.getJSON(requestURL, function(data){
        $.each(data, function(key, value) {
            $('body').append($('<div>' + data[0].name, {

            }));
            console.log(data);
        });

    });

My console is returning two objects that look like this

Array[3], Array[3]] Array[3]: 
Array[3] [Array[3], Array[3]] 

So I know it's getting data back I just need to be able to pick what I want a append it to the DOM. I've tried ten different variations but nothing works. Please help!?


Solution

  • You just need to iterate one more time inside first iteration. You have one array that holds array of objects. So try something like this

    http://jsfiddle.net/mnth1xe1/5/

    $.each(data, function(key, val) {
        $.each(val, function(key, value) {
    
            console.log(value.countTxt);
        });
    
    });