-1

About an hour ago I made a post (that I have deleted) about getting contents of a JSON file. It struck me only later that JSON is simply accessible as a JS Object, so accessing the object isn't an issue any longer. However, now I want to recursively add elements to an HTML list and I am making a logical flow error somewhere, but I just can't figure out how to solve it. (I've been working five hours straight, so that might be a cause).

function init(src) {
    $.getJSON(src, {
        format: "json"
    }).done(function (data) {
        var json = $(data);
        main(json);
    });
}

function main(json) {
    var base = $("body");
    base.html(traverse(json[0]));
}

function traverse(node) {
    var newList = $("<ol/>");
    if (typeof node == "object") {
        $.each(node, function (k, v) {
            var newItem = $('<li><a href="#">' + k + '</a></li>');
            traverse(v);
            newItem.appendTo(newList);
        });
    } else {
        // Not sure if `$(this)` will simply return this item's name?
        var newItem = $('<li><a href="#">' + $(this) + '</a></li>');
        newItem.appendTo(newList);
    }

    return newList;
}

init("myjson.json");

Example input of myjson.json:

{
  "S": {
    "NP": {
      "N": "i"
    },
    "VP": {
      "V": "like",
      "NP": {
        "Det": "the",
        "N": "bananas"
      }
    }
  }
}

The recursion stops after a single item is added, so the output is:

<ol><li>S</li></ol>

But the expected output is:

<ol>
  <li>S
    <ol>
      <li>NP
        <ol>
          <li>N
            <ol>
              <li>i</li>
            </ol>
          </li>
        </ol>
      </li>
      <li>VP
        <ol>
          <li>V
            <ol>
              <li>like</li>
            </ol>
          </li>
          <li>NP
            <ol>
              <li>Det
                <ol>
                  <li>the</li>
                </ol>
              </li>
              <li>N
                <ol>
                  <li>bananas</li>
                </ol>
              </li>
            </ol>
          </li>
        </ol>
      </li>
    </ol>
  </li>
</ol>
Community
  • 1
  • 1
Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

1 Answers1

1

The problem is that, while you are traversing the data recursively, you do not use the returned result of the recursive call.

var newItem = $('<li><a href="#">' + k + '</a></li>');
// output of this call is not used
traverse(v);
newItem.appendTo(newList);

Once you append the result, it works:

traverse(v).appendTo(newItem);

JSFiddle

James Brierley
  • 4,630
  • 1
  • 20
  • 39