将JSON对象值显示到表中

时间:2016-01-20 18:36:21

标签: javascript jquery json gson

我的Json数组格式,我试图在html表中显示locTable中的值

"categoryName": [
"Construction",
"Emergency Response",
"Equipment",
"General",
"General Safety",
"Marine",
"Materials",
"Products",
"Protection of Workers",
"Transport",
"Workplace"
],
"locTable": [
{
  "evaluationPercent": 100,
  "relevancePercent": 100,
  "category": "Workplace",
  "ldloc": []
},
{
  "evaluationPercent": 100,
  "relevancePercent": 100,
  "category": "Workplace",
  "ldloc": []
},
{
  "evaluationPercent": 100,
  "relevancePercent": 100,
  "category": "Workplace",
  "ldloc": []
},

我的HTML代码

 <table  class="red" style="width: 100%; height: 100%;">
 <thead>
 <tr>
 <th>Category</th>
 <th class="right">Rele Completed</th>
 <th class="right">Eval Completed</th>
 </tr>
 </thead>
 <tbody id="display" class="no-border-x">
 </tbody>
 </table>

我尝试使用jQuery迭代Json对象,但是我无法显示正确的值,我的代码的结果显示Undefined。我试图获得结果的代码。

 var trHTML = '';
 jQuery.each(json.locTable, function (k, item) {                   
 trHTML += '<tr><td>' + item.category + '</td><td>'       
 +item.evaluationPercent + '</td><td>' +item.relevancePercent +
 '</td></tr>';
 });
 jQuery('#display').append(trHTML);

3 个答案:

答案 0 :(得分:0)

我不知道你是不是发布了你的整个JSON,但是因为它目前是无效的。这是有效的:

var json = {
  "categoryName": [
    "Construction",
    "Emergency Response",
    "Equipment",
    "General",
    "General Safety",
    "Marine",
    "Materials",
    "Products",
    "Protection of Workers",
    "Transport",
    "Workplace"
  ],
  "locTable": [{
    "evaluationPercent": 100,
    "relevancePercent": 100,
    "category": "Workplace",
    "ldloc": []
  }, {
    "evaluationPercent": 100,
    "relevancePercent": 100,
    "category": "Workplace",
    "ldloc": []
  }, {
    "evaluationPercent": 100,
    "relevancePercent": 100,
    "category": "Workplace",
    "ldloc": []
  }]
};

它有效,请参阅:https://jsfiddle.net/ve7r4422/

答案 1 :(得分:0)

乍一看,我认为xml格式存在问题。

有几篇文章可能会解决您的问题,例如:

Convert JSON array to an HTML table in jQuery

答案 2 :(得分:0)

var json = {
  "locTable": [{
    "evaluationPercent": 80,
    "relevancePercent": 100,
    "category": "Workplace",
    "ldloc": []
  }, {
    "evaluationPercent": 90,
    "relevancePercent": 70,
    "category": "Workplace",
    "ldloc": []
  }, {
    "evaluationPercent": 100,
    "relevancePercent": 40,
    "category": "Workplace",
    "ldloc": []
  }]
};

jQuery('#display').append($.map(json.locTable, function(record){
  return '<tr><td>'+ record.category +'</td><td>'+ record.evaluationPercent +'</td><td>'+ record.relevancePercent +'</td></tr>';
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="red" style="width: 100%; height: 100%;">
  <thead>
    <tr>
      <th>Category</th>
      <th class="right">Rele Completed</th>
      <th class="right">Eval Completed</th>
    </tr>
  </thead>
  <tbody id="display" class="no-border-x"></tbody>
</table>