2016-07-22 55 views
3

我試圖找到一種方法將動態JSON對象轉換爲有效的HTML網頁。這個想法是能夠將物聯網設備需要顯示的內容推送到雲中,並讓用戶能夠輸入和保存配置。來自JSON對象的動態UI

JSON的會是這個樣子

{ 
    "loginConfiguration": { 
    "username": "string", 
    "password": "string", 
    "hostname": "string" 
    }, 
    "systemConfiguration": { 
    "numberOfEvents": "int" 
    } 
} 

和理想的輸出將是下一個被稱爲loginConfiguration第3個文本框與字符串輸入,然後用1個整數輸入另一部分。但請注意,json對象會有所不同,應該能夠適應這一點。

我打開技術堆棧,但它似乎是最有可能的JavaScript/jQuery。如果你有一個像Dart這樣的替代品,那麼請說明如何實現這一點。

回答

0

我希望你能理解我的代碼,並且我已經使它像動態一樣,只有你需要知道的json的元素纔是初始對象。例如我已經使用:

var json = 
'{ 
    "result" : { 
     "loginConfiguration" : { 
      "username" : "string", 
      "password" : "string", 
      "hostname" : "string" 
     }, 
     "systemConfiguration" : { 
      "numberOfEvents" : "int" 
     } 
    } 
}' 

這裏是的jsfiddle:https://jsfiddle.net/22dx9u7d/

這裏是jQuery代碼

var sectionHtml = "" 
var controlHtml = "" 

var data = JSON.parse(json) 


    $(data.result).each(function(index,value){ 

     //Counts how many sections there are 
     var countSections = Object.keys(this).length; 
     var i = 0 

     //Goes through sections 
     while(i != countSections){ 
     var sectionName = Object.keys(this)[i] 

     sectionHtml = "<div id='"+ sectionName +"'><h1>Section:"+ sectionName +"</h1>" 

      //Goes through sections 
      $(data.result[Object.keys(this)[i]]).each(function (index, value) { 



       //Count controls inside section 
       var countControls = Object.keys(this).length 
       var j = 0 

       //For each control take data needed 
       while(j != countControls){  
        var controlName = Object.keys(this)[j] 
        var controlType = value[controlName] 

         //Do your checking for control type and generate html 
         if(controlType == 'string'){ 
          sectionHtml += '<label>'+ controlName +' : </label><input type="text" id="'+ controlName +'" /><br />' 
         }else if(controlType == 'int'){ 
          sectionHtml += '<label>'+ controlName +' : </label><input type="number" id="'+ controlName +'" /><br />' 
         } 


        j++ 
       } 

      }); 
      i++ 

      //Close section html 
      sectionHtml += "</div>" 
      //Append it to html 
      $("#appendDiv").append(sectionHtml) 


     } 

    })