2015-08-15 79 views
1

我需要以定製格式將json數據導出到html表格中。將json數據導出到html表格格式

var data =[ { "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }]; 

所需的輸出格式如下

ID Sl.No.
1 1 0325 25 1 1 0430 30 1 1 2011 15 1 1 1915 80 1 2 0325 40 1 2 0430 30 1 2 2011 20 1 2 1915 100 1 3 0325 40 1 3 0430 25 1 3 2011 20 1 3 1915 100 1 4 0325 4 1 4 0430 2 1 4 2011 1 1 4 1915 20

+0

@ taylorc93我新的json。我無法爲此代碼創建邏輯。 –

+0

@Arthik首先使用_native JavaScript Object_,看看你是否可以得到這個工作。 –

回答

1

var data =[ { "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }]; 
 
$a = $('#values') 
 
$.each(data, function(index, value) { 
 
    $thisRow = $('<tr/>') 
 
    .append($('<td>' + value['ID'] + '</td>')) 
 
    .append($('<td>' + value['Sl.No.'] + '</td>')) 
 
    .append($('<td>' + '0325' + '</td>')) 
 
    .append($('<td>' + value['325'] + '</td>')) 
 
    for (var i = 0; i < 3; i++) { 
 
    if (i == 0) 
 
     key = '430'; 
 
    if (i == 1) 
 
     key = '2011'; 
 
    if (i == 2) 
 
     key = '1915'; 
 
    $thisRow = $('<tr/>') 
 
     .append($('<td>' + value['ID'] + '</td>')) 
 
     .append($('<td>' + value['Sl.No.'] + '</td>')) 
 
     .append($('<td>' + key + '</td>')) 
 
     .append($('<td>' + value[key] + '</td>')); 
 
    $a.append($thisRow); 
 
    } 
 

 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<table id="values"></table>

0

使用下面的代碼

var data ='[{ "ID":1, "Sl.No.":1, "325":25, "430":30, "2011":15, "1915":80 }, { "ID":1, "Sl.No.":2, "325":40, "430":30, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":3, "325":40, "430":25, "2011":20, "1915":100 }, { "ID":1, "Sl.No.":4, "325":4, "430":2, "2011":1, "1915":20 }]'; 
 

 
var str = JSON.parse(data); 
 
var temp= ''; 
 

 
$.each(str,function(index, value){ 
 

 
    var id = value.ID; 
 
    var slNo = value['Sl.No.']; 
 
    
 
    $.each(value, function(ind, val){ 
 
    
 
     if(ind !='ID' && ind != 'Sl.No.') 
 
        temp+='<tr><td>'+id+'</td><td>'+slNo+'</td><td>'+ind+ 
 
        '</td><td>'+val+'</td></tr>';    
 
    }); 
 
}); 
 

 
$('#myTable tbody').append(temp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table id="myTable" border="1"> 
 
    <thead> 
 
     <th>Head 1</th> 
 
    <th>Head 2</th><th>Head 3</th><th>Head 4</th> 
 
    </thead> 
 
    <tbody></tbody> 
 
    </table>