5

I currently have this:

    $.getJSON('test.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');
    });

test.json looks like this:

{"key1":{"key11":"value11","key12":"value12"},"key2":"value2","key3":"value3"}

I'm getting:

[object Object]
value2
value3

How can I change it so it will loop through all the nested items regardless of how many nested values I have?

So for the above example I will get

value1
    value11
    value12
value2
value3
Or Weinberger
  • 7,332
  • 23
  • 71
  • 116
  • Why do you expect `value1` to be displayed? – pimvdb Dec 18 '11 at 18:33
  • @pimvdb not expecting it, my question is how do I make it display as a nested
      ? also, is it possible to alter the code in a way that will automatically add nested
        's according to the nesting in the JSON?
    – Or Weinberger Dec 18 '11 at 18:34

2 Answers2

6

You can make a recursive loop function, but you'd have a problem: when a property is an object, there is no text to display because there is no string. So, you'll end up with:

- - value11
  - value12
- value2
- value3

because while value2 is the string to display for item #2, it is an object that's displayed for item #1.

Anyway, this is what I made up: http://jsfiddle.net/uXww2/.

// obj is the object to loop, ul is the ul to append lis to
function loop(obj, ul) {
    $.each(obj, function(key, val) {
        if(val && typeof val === "object") { // object, call recursively
            var ul2 = $("<ul>").appendTo(
                $("<li>").appendTo(ul)
            );

            loop(val, ul2);
        } else {
            $("<li>", {
                id: key
            }).text(val).appendTo(ul);
        }
    });
}

$.getJSON('test.json', function(data) {
  var ul = $("<ul>");

  loop(data, ul);

  ul.addClass("my-new-list").appendTo('body');
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • @Or W: You'd have to give the li inside ul2 some text (the key variable). – pimvdb Dec 18 '11 at 20:13
  • this does not take arrays into account, you probably should write `$.isPlainObject(val) || $.isArray(val)` – Christoph Jul 17 '12 at 09:45
  • using `typeof` is not recommended, since `typeof null === "object"` yields true – Christoph Jul 17 '12 at 10:47
  • @Christoph: True. The OP only deals with strings, though (no arrays/`null`/etc), but I'll edit. – pimvdb Jul 17 '12 at 10:58
  • Almost 3 years since this was posted and still useful now. Thank you for helping me solve the issue I have had for the last few days. – Johnrad Apr 08 '15 at 15:00
  • how would you do this without the use of recursive calls ? – serup Jul 13 '17 at 05:47