简体   繁体   English

以html表格格式显示json数据

[英]Display json data in table format in html

I have the following json which is a response from ajax call. 我有以下json是ajax调用的响应。

[  
   {  
      "Key1":"value1",
      "key2":{  
         "subkey1":"subvalue",
         "subkey2":"subvalue2"
      }
   },
   {  
      "Key1":"value1",
      "key2":{  
         "subkey1":"subvalue3",
         "subkey2":"subvalue4"
      }
   }
]

I have to display values of key 2 in html table. 我必须在html表中显示键2的值。

subkey1         subkey2 
---------       ---------
subvalue1       subvalue2
subvalue3       subvalue4

Please note that number of columns are also dynamic. 请注意,列数也是动态的。

You can get the keys from first object with Object.keys() to set the header. 您可以使用Object.keys()从第一个对象获取键来设置标题。 Then loop through the array with each() to set the table body. 然后使用each()遍历数组以设置表主体。

Try the following way: 请尝试以下方式:

 var arrData = [ { "Key1":"value1", "key2":{ "subkey1":"subvalue1", "subkey2":"subvalue2" } }, { "Key1":"value1", "key2":{ "subkey1":"subvalue3", "subkey2":"subvalue4" } } ] var col = Object.keys(arrData[0].key2); $('table').append('<thead><tr><th>' +col[0]+'</th><th>' +col[1]+'</th></tr></thead>'); $(arrData).each(function(i,v){ $('#tbody').append('<tr><td>' +v.key2.subkey1+'</td><td>' +v.key2.subkey2+'</td>'); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody id="tbody"></tbody> </table> 

      var response = [  
           {  
              "Key1":"value1",
              "key2":{  
                 "subkey1":"subvalue",
                 "subkey2":"subvalue2"
              }
           },
           {  
              "Key1":"value1",
              "key2":{  
                 "subkey1":"subvalue3",
                 "subkey2":"subvalue4"
              }
           }
        ];

    var columns = [];

    if(response.length >0) {
         var item = response[0];
         columns = Object.keys(item['key2']);
    }

    var htmlStr = '<table><tr>';

    columns.map(function(col){
      htmlStr += '<th>'+col+'</th>'; 
    });

    htmlStr += '</tr>';



    response.map(function(item){
      htmlStr += '<tr>';
      columns.map(function(colName){
         htmlStr += '<td>' + item.key2[colName]+'</td>';
      });
      htmlStr += '</tr>';
    });

    document.getElementById('table').innerHTML = htmlStr + '</table>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM