首页 > 解决方案 > 如何将json值转换为html表

问题描述

我想要 json 代码以及如何将该 json 数据转换为 html 表。重要的是如何将 json 值转换为 html 中的 th(header)。 在此处输入图像描述

标签: htmljsondatatable

解决方案


查看https://jsfiddle.net/nt56wuox/3/以获取纯 javascript 和 HTML 的基本示例。

html

<html>
<body>
  <input id='inAttr' type='text' placeholder='Enter attr' >
  <button onClick='calculate(document.getElementById("inAttr").value)' > Show table  </button>
  <div id='result'>  </div>
</body>
</html>

Javascript

data = [
{code:'101' , attr:'Body' , attr_value: 'SS04'},
{code:'102' , attr:'Body' , attr_value: 'SS04'},
{code:'103' , attr:'Float' , attr_value: 'SS0X'},
{code:'104' , attr:'Spring' , attr_value: 'SS0X'},
]

function calculate(attr){

  const tableData = data
  .filter(row=>row.attr === attr)
    
  console.log({attr, tableData}); 
  
  var html = '<table>';
  html+=`<tr><th>Code</th><th>${attr}</th></tr>`
  tableData.forEach(row=>{
  html+=`<tr><td>${row.code}</td><td>${row.attr_value}</td></tr>`
  })
  html += '<table>';

  document.getElementById('result').innerHTML = html;
  return tableData;
}

您可能需要考虑阅读有关 HTML、JS 和 JSON 以及可能的常见框架之一,例如 Angular / React


推荐阅读