Generate unordered list from JSON Data?

后端 未结 3 2090
予麋鹿
予麋鹿 2020-12-08 11:53

I\'d like to generate a tree view of my JSON data. Therefore it would be nice to parse the JSON data into a multi-level (!) unordered HTML list

3条回答
  •  醉话见心
    2020-12-08 12:45

    Here is a complete pure javascript solution. Recursive traverse the JSON object and construct you ul and li's as you go. It's better for not to add elements to the DOM one at a time, though.

    HTML

     

      JAVASCRIPT

      var jsonObj ={"labels":[ {"labelFont":"35pt Calibri","labelLocation":{"x":0.1483, "y":0.75},  "labelText":"fluffer"},{"labelFont":"35pt Calibri","labelLocation":{"x":0.666, "y":0.666},  "labelText":"nutter"}]}; //some json to display
      
      var listEl =document.getElementById('JSONunorderedList');
      makeList(jsonObj,listEl);
      
      function makeList( jsonObject, listElement){
          for(var i in jsonObject){//iterate through the array or object
              //insert the next child into the list as a 
    • var newLI = document.createElement('li'); if (jsonObject[i] instanceof Array){ newLI.innerHTML=i+": ARRAY"; newLI.className="arrayOrObject"; //add a class tag so we can style differently } else if ( jsonObject[i] instanceof Object){ newLI.innerHTML=i+": OBJECT"; newLI.className="arrayOrObject"; //add a class tag so we can style differently } else newLI.innerHTML=i+': '+jsonObject[i]; listElement.appendChild(newLI); //insert a
        for nested nodes if (jsonObject[i] instanceof Array || jsonObject[i] instanceof Object){ var newUL = document.createElement('ul'); //newUL.innerHTML=i; listElement.appendChild(newUL); makeList(jsonObject[i],newUL); } } }
    • das fiddle http://jsfiddle.net/honkskillet/LvMnG/

    提交回复
    热议问题