【问题标题】:How to covert json value in to html table如何将json值转换为html表
【发布时间】:2020-12-30 08:56:58
【问题描述】:

我想要 json 代码以及如何将 json 数据转换为 html 表。重要的是如何将 json 值转换为 html 中的 th(header)。

【问题讨论】:

  • 你使用什么后端语言?
  • 请输入你试过的代码
  • 你使用 JavaScript @Gokul

标签: html json datatable


【解决方案1】:

查看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

【讨论】:

    【解决方案2】:

    如果你使用 JS。

    尝试将表格构建为字符串,然后将其插入元素中,

    const json = [{
        code: 101,
        attribute: "Body",
        attribute_values: "S101"
      },
      {
        code: 102,
        age: "float",
        attribute_values: "S102"
      }
    ]
    
    function buildTable() {
    
      let tab = `<table><thead><tr><th>Code</th><th>Body</th></tr></thead><tbody>`
       
      json.forEach((elem) => {
      tab += `<tr><td>${elem.code}</td><td>${elem.attribute_values}</td></tr> `
      });
      
      tab += `</tbody></table>`
    
     document.getElementById("insTab").innerHTML = tab;
      
    }
    buildTable();
    &lt;div id="insTab"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2017-06-06
      • 2011-08-12
      • 1970-01-01
      • 2013-09-03
      • 2014-02-23
      • 2014-10-28
      • 2021-06-05
      • 2019-11-24
      相关资源
      最近更新 更多