从JSON数据创建html表 [英] Creating html table from JSON data

查看:74
本文介绍了从JSON数据创建html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文件,其中包含此代码段。

I have a an html file that has this snippet in it.

<div>
    <table id="apps"></table>
</div>

我收到的JSON数据如下:

I am receiving JSON data that looks like this:

{
    "1": [
        {
            "A": "",
            "B": "",
            "C": "",
            "D": "",
            "E": ""
        }
    ]
}

只有一个1,但那里可以是1列表中的多个字典。在这个例子中,我们在列表中只有一个 {} [] ,但是可能存在多个 {} 包含五个项目,如上所示。

There will be exactly one "1" , but there can be more than one dictionary within the list of "1". In this example, we only have one {} within the list, [] , but there can exist multiple {} of containing exactly five items like what is shown above.

我想根据这些数据创建一个表,其中每行代表 {} 中的 [] 并且有五列分别代表A,B,C,D,E。

I want to create a table from this data, where each row represents a single {} within the [] and has five columns representing A, B, C, D, E respectively.

我不确定我是否应该有这个结构,标签已经在我的html中(这不在我提供的html代码中)然后填充这些标签或应该我的函数在我的html文件中加载这些数据,访问表id =apps并创建这些标签,然后填充这些标签?哪个更好?如何有效地实现这一目标?

I am unsure if I should have the structure of this, the tags already in my html(this is not in my html code provided) and then populate these tags or should my function that loads this data in my html file, access table id="apps" and create these tags and then populate these tags? Which is better? and How might one accomplish this efficiently?

推荐答案

试试这个简单的工作示例。我希望它能按照你的期望工作。

Try this simple working example. I hope it will work as per your expectation.

var dataObj = {
    "1": [{
            "A": "",
            "B": "",
            "C": "",
            "D": "",
            "E": ""
        },
        {
            "F": "",
            "G": "",
            "H": "",
            "I": "",
            "J": ""
        },
        {
            "K": "",
            "L": "",
            "M": "",
            "N": "",
            "O": ""
        }
    ]};

var dictionaryData = dataObj["1"];

for (var i in dictionaryData) {
  var table = document.getElementById("apps");
  var tr = document.createElement("tr");
  var td = document.createElement("td");
  
  for (var key in dictionaryData[i]) {
    var txt = document.createTextNode(key);
    td.appendChild(txt);
    tr.appendChild(td);
  }
  table.appendChild(tr);
}

table, td {
    border: 1px solid black;
}

<div>
    <table id="apps"></table>
</div>

这篇关于从JSON数据创建html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆