Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

javascript - 将json数据转换为html表(Convert json data to a html table [closed])

Is there any jQuery or javascript library that generates a dynamic table given json data?(是否有任何jQuery或javascript库根据给定的json数据生成动态表?)

I don't want to define the columns, the library should read the keys in the json hash and generate columns.(我不想定义列,该库应该读取json哈希中的键并生成列。)

Of course, I can myself iterate through the json data and generate the html table.(当然,我可以自己遍历json数据并生成html表。)

I just want to know if any such library exists which I can simply reuse.(我只想知道是否存在可以简单重用的此类库。)   ask by Manish Mulani translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Thanks all for your replies.(感谢大家的答复。)

I wrote one myself.(我自己写了一个。) Please note that this uses jQuery.(请注意,这使用jQuery。)

Code snippet:(程式码片段:)

 var myList = [ { "name": "abc", "age": 50 }, { "age": "25", "hobby": "swimming" }, { "name": "xyz", "hobby": "programming" } ]; // Builds the HTML Table out of myList. function buildHtmlTable(selector) { var columns = addAllColumnHeaders(myList, selector); for (var i = 0; i < myList.length; i++) { var row$ = $('<tr/>'); for (var colIndex = 0; colIndex < columns.length; colIndex++) { var cellValue = myList[i][columns[colIndex]]; if (cellValue == null) cellValue = ""; row$.append($('<td/>').html(cellValue)); } $(selector).append(row$); } } // Adds a header row to the table and returns the set of columns. // Need to do union of keys from all records as some records may not contain // all records. function addAllColumnHeaders(myList, selector) { var columnSet = []; var headerTr$ = $('<tr/>'); for (var i = 0; i < myList.length; i++) { var rowHash = myList[i]; for (var key in rowHash) { if ($.inArray(key, columnSet) == -1) { columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } $(selector).append(headerTr$); return columnSet; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body onLoad="buildHtmlTable('#excelDataTable')"> <table id="excelDataTable" border="1"> </table> </body> 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...