ndesign11
ndesign11

Reputation: 1779

Ajax and json issue

I have a little ajax call to load json data into the DOM but it's not working. When I look at the net tab I see that its loaded but no data is on the actual page. It just says [object Object]

   $.getJSON('json/redstone.json', function(data) {
   var items = [];

   $.each(data, function(key, val) {
       items.push('<li id="' + key + '">' + val + '</li>');
   });

   $('<ul/>', {
      'class': 'my-new-list',
       html: items.join('')
      }).appendTo('body');
   });

Here is my JSON

{
"allconfig": {
    "card.inserted": {
        "value": "Not Inserted",
            "type": "enum",
            "range": "",
            "clone": false,
            "archive": false,
            "access": "R"
    },
        "card.cisproc": {
        "value": "Processed",
            "type": "string",
            "range": "",
            "clone": false,
            "archive": false,
            "access": "R"
    },
        "card.mfgid": {
        "value": "",
            "type": "string",
            "range": "",
            "clone": false,
            "archive": false,
            "access": "R"
    }
}
}

Upvotes: 1

Views: 76

Answers (2)

huysentruitw
huysentruitw

Reputation: 28151

val is actually an object in your JSON data. And if you do $.each over the data, you will only get the allconfig element. So you might want to enumerate over data.allconfig instead.

So you might want to display the val's value property instead, like this:

$.getJSON('json/redstone.json', function(data) {
var items = [];

$.each(data.allconfig, function(key, val) {
    items.push('<li id="' + key + '">' + val.value + '</li>');
});

$('<ul/>', {
   'class': 'my-new-list',
    html: items.join('')
   }).appendTo('body');
});

Here is a working jsFiddle

Upvotes: 2

Paul Richter
Paul Richter

Reputation: 11081

Another method you can try is iterating over the JSON object using regular javascript iteration, like so:

for(var key in data){
    var value = data[key];
    items.push('<li id="' + key + '">' + value + '</li>');
}

Edit: I just realized your data structure, as someone pointed out in the comments, has sub, or nested objects. My method, by itself, will only work for the first level of key:value pairs. If you'd like to make your iteration function a little more generic, you can use recursion to properly dive through your structure, like so:

function buildData(data){
    for(var key in data){
        var value = data[key];
        if(typeof(value) == "object"){
          nestedData = buildData(value);
          items.push('<li id="' + key + '">' + nested + '</li>');
          // I'm not sure how you want to handle your nested objects, so place
          // here what you need and whatever else you need to do to handle
          // your nested object situation.
        }else{
            items.push('<li id="' + key + '">' + value + '</li>');
        }
    }
}

Upvotes: 0

Related Questions