Skip to content Skip to sidebar Skip to footer

Generate Html Table From Json Data

How can i generate a HTML table from JSON data? I have the following JSON DATA: [ { name: 'Condition' value: 'New' }, { name: 'Year' value: '2007' }, {

Solution 1:

you JSON data's format is not current, you need to add ',' before the 'value' index.

<!DOCTYPE HTML>
<html lang = "zh">
  <head>
    <meta charset="utf-8" />
    <title>
      jQuery Table
    </title>
    <script src="js/jquery.min.js" type="text/javascript"></script>
  </head>
<body>
    <div id = "divTable"></div>
<script>
var data = [
  {
    name: "Condition"
    , value: "New"
  },
  {
    name: "Year"
    , value: "2007"
  },
  {
    name: "Manufacturer"
    , value: "Audi"
  },
  {
    name: "Model"
    , value: "A4"
  },
  {
    name: "Type"
    , value: "Limousine"
  },
  {
    name: "Options"
    , value: "Full"
  }
];
var html = '<table width="779" border="1" cellpadding="0" cellspacing="0">';
html += '<tr><td width="104">' + data[0].name + '</td><td width="318">' + data[0].value + '</td>';
html += '<td width="176">' + data[1].name + '</td><td width="171">' + data[1].value + '</td></tr>';
for(var i = 2; i < data.length; i++) {
  if(i % 2 == 0)
    html += '<tr>';
  html += createEleHtml(data[i]);
  if(i % 2 == 1)
    html += '</tr>';
}

function createEleHtml(ele){
  if(ele && ele.name) return '<td>' + ele.name + '</td><td>' + ele.value + '</td>';
};

html += '</table>';
$("#divTable").html(html);
</script>
</body>
</html>

Post a Comment for "Generate Html Table From Json Data"