Turning nested JSON into an HTML nested list with Javascript

后端 未结 3 1910
忘了有多久
忘了有多久 2021-02-06 13:03

I\'m fairly new to using JSON (as opposed to XML) and am currently working purely with Javascript to digest, parse and display my returned JSON data.

I\'m using the JSON

3条回答
  •  终归单人心
    2021-02-06 13:37

    Here's some fairly simple code that creates a

      element for each object, and a
    • element for each portion. You can add a quick check to test the child variable against things like "class" if you want to add a special case.

      function jsonToHtmlList(json) {
          return objToHtmlList(JSON.parse(json));
      }
      
      function objToHtmlList(obj) {
          if (obj instanceof Array) {
              var ol = document.createElement('ol');
              for (var child in obj) {
                  var li = document.createElement('li');
                  li.appendChild(objToHtmlList(obj[child]));
                  ol.appendChild(li);
              }
              return ol;
          }
          else if (obj instanceof Object && !(obj instanceof String)) {
              var ul = document.createElement('ul');
              for (var child in obj) {
                  var li = document.createElement('li');
                  li.appendChild(document.createTextNode(child + ": "));
                  li.appendChild(objToHtmlList(obj[child]));
                  ul.appendChild(li);
              }
              return ul;
          }
          else {
              return document.createTextNode(obj);
          }
      }
      

      This won't do exactly what you want, because your JSON doesn't make sense. Objects in JavaScript, and therefore JSON, are maps, and so you can't have more than one child with the same name. You'll need to turn your multiple "node"s into an array, as Cédric points out.

提交回复
热议问题