【问题标题】:How do I create a table from remote JSON?如何从远程 JSON 创建表?
【发布时间】:2020-07-11 05:36:46
【问题描述】:

我知道如何从 JSON 创建表。下面是示例代码。但我不知道如何连接到包含要在制表功能中使用的 JSON 内容的远程 URL。我找到了 json 页面的 this url,我想用信息(大陆、国家、病例、死亡、恢复和上次更新)创建同一个表。与示例中的表格结果非常相似。如果关于这个话题的讨论存在并且有正确的结果,请写在评论中,但不要删除这个话题。

TABLE.HTML(JSON 在页面中,我想从远程 JSON 创建表)

<!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input {
            font:14px Verdana;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>

    <p id="showData"></p>
</body>

<script>

        var myBooks = [
            {
                "Book ID": "1",
                "Book Name": "Computer Architecture",
                "Category": "Computers",
                "Price": "125.60"
            },
            {
                "Book ID": "2",
                "Book Name": "Asp.Net 4 Blue Book",
                "Category": "Programming",
                "Price": "56.00"
            },
            {
                "Book ID": "3",
                "Book Name": "Popular Science",
                "Category": "Science",
                "Price": "210.40"
            }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);

</script>
</html>

【问题讨论】:

    标签: javascript json web-scraping html-table


    【解决方案1】:

    您将首先使用XMLHttpRequestFetch 尝试获取远程数据,然后通过JSON.parse 对其进行转换。如果成功,该对象可用于生成您的表格,就像您在示例代码中一样。

    如果您不喜欢使用“vanilla”JS,您可以找到大量用于 XMLHttpRequest 和 Fetch 的库。

    【讨论】:

      【解决方案2】:

      您的数据源不再提供数据。因此,我将其更改为每天反映约翰霍普金斯大学(马里兰州巴尔的摩)编制的统计数据的地方。由于此数据包含 时间序列,因此我必须在将它们放入下表之前对其进行稍微预处理。格式化(=colouring)最好通过几行 CSS 来完成:

      const num=s=>+s.replace(/[^0-9]/g,''),
        cols=["country","cases","deaths","recovered","deathrate"];
      fetch('https://pomber.github.io/covid19/timeseries.json').then(r=>r.json()).then(o=>{
        var D=Object.keys(o).sort().map(c=>{
          let dat=Object.values(o[c].slice(-1)[0]);
          dat[0]=c;dat.push((100*dat[2]/dat[1]).toFixed(2)+'%');
          return dat
        })
        document.querySelector('table').innerHTML='<tr>'+
        cols.map(s=>
          `<th>${s}</th>`).join('')+'</tr><tr>'
           +D.map(r=>`<td>${r.join('</td><td>')}</td>`)
             .join('</tr><tr>')+'</tr>';
       })
      th:first-child {text-align:left}
      th:nth-child(n+2), td:nth-child(n+2) {text-align:right}
      th:nth-child(2) {background-color: #00aa22}
      th:nth-child(3) {background-color: #ffff00}
      th:nth-child(4) {background-color: #ff0000}
      th:nth-child(5) {background-color: #ff9900}
      td:nth-child(2) {background-color: #55ee77}
      td:nth-child(3) {background-color: #ffff55}
      td:nth-child(4) {background-color: #ff0000}
      td:nth-child(5) {background-color: #ffb84d}
      &lt;table&gt;&lt;/table&gt;

      纯粹出于兴趣,我在表格中添加了一些排序功能。点击任一列标题按该列排序(再次点击逆序):

      const num=s=>+s.replace(/[^0-9]/g,''),
        cols=["country","cases","deaths","recovered","deathrate"];
      const tblsort=ev=>{const e=ev.target; if (e.tagName=='TH'){
         const i=[...e.parentNode.children].indexOf(e); srtdir[i]=srtdir[i]>0?-1:1;
         [...tbd.children].sort(i>0?srtnum(i):srttxt(i)).forEach(tr=>tbd.appendChild(tr));
        }
      };
      const srtdir=[];
      const srtnum=i=>(a,b)=>srtdir[i]*num(a.children[i].textContent)-num(b.children[i].textContent);
      const srttxt=i=>(a,b)=>srtdir[i]*a.children[i].textContent.localeCompare(b.children[i].textContent);
      fetch('https://pomber.github.io/covid19/timeseries.json').then(r=>r.json()).then(o=>{
        var D=Object.keys(o).sort().map(c=>{
          let dat=Object.values(o[c].slice(-1)[0]);
          dat[0]=c;dat.push((100*dat[2]/dat[1]).toFixed(2)+'%');
          return dat
        })
        document.querySelector('table').innerHTML='<thead><tr>'+
        cols.map(s=>
          `<th>${s}</th>`).join('')+'</tr></thead><tbody><tr>'
           +D.map(r=>`<td>${r.join('</td><td>')}</td>`)
             .join('</tr><tr>')+'</tr></tbody>';
        tbd=document.querySelector('tbody');
        thd=document.querySelector('thead').addEventListener('click',tblsort);
       })
      th {cursor:pointer}
      th:first-child {text-align:left}
      th:nth-child(n+2), td:nth-child(n+2) {text-align:right}
      th:nth-child(2) {background-color: #00aa22}
      th:nth-child(3) {background-color: #ffff00}
      th:nth-child(4) {background-color: #ff0000}
      th:nth-child(5) {background-color: #ff9900}
      td:nth-child(2) {background-color: #55ee77}
      td:nth-child(3) {background-color: #ffff55}
      td:nth-child(4) {background-color: #ff0000}
      td:nth-child(5) {background-color: #ffb84d}
      &lt;table&gt;&lt;/table&gt;

      【讨论】:

      • 谢谢它非常有帮助。
      • 我想问一下如何重新着色案例的标题背景:黄色,死亡:红色,恢复:绿色和死亡率:橙色。并且所有病例值都变为淡黄色,所有死亡值变为红色,所有恢复值:淡绿色和所有死亡率值:淡橙色......当然我可以使用 tr, td 的 bgcolor 但如果我重新着色一些tr,整个内容都是彩色的。不仅仅是我需要的。那你能问我怎么做吗?谢谢
      • 这是想要的颜色,第一种颜色是标题的颜色,第二种颜色是所有值的颜色:green:00aa22, 55ee77 / yellow: ffff00, ffff55 / red: ff0000, ff0000 /橙色:ff9900、ffb84d
      • 再次感谢您:-)
      猜你喜欢
      • 1970-01-01
      • 2015-08-31
      • 2015-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多