如何使用json数据创建表

时间:2014-03-03 00:04:32

标签: javascript jquery json handlebars.js

我的json部分:

var Json = {
 "Sample" : {
   "Sample Demo": {
     "1": {"JAN": {"ID": "1","Name": "Jim"}},
     "2": {"FEB": {"ID": "2","Name": "Jack" } }
    }},
 "Idname" : "2",
  "Date" : "01/28/2014",
  "State" : "1"
 }

我想从json上面创建表。我的表头将是JAN,FEB和数据将是ID和Name。

2 个答案:

答案 0 :(得分:1)

使用jQuery:

var content = "<table>";
jQuery.each(Json.Sample["Sample Demo"], function(i, val) {
  jQuery.each(val, function(j, v) { content += "<tr><td>"+v.ID+","+v.Name +"</tr></td>";});
});
content += "</table>"

答案 1 :(得分:0)

查看this answer.

作者概述了以下解决方案:

在HTML中定义模板:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

使用string.format替换变量:

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template); 

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};
相关问题