【问题标题】:How to build a dynamic html table from json data using node js?如何使用节点 js 从 json 数据构建动态 html 表?
【发布时间】:2018-12-13 18:32:52
【问题描述】:

在nodejs + express + postgres有一个小项目,用于自学。通过请求 Postgres,我获取 json 格式的数据,然后将 express 工具上的数据呈现到 ejs 模板。问题是如何将此 json 添加到 html 中的动态表中。

对数据库的请求如下所示

    const pool = new pg.Pool(config);

 router.get('/index', (req, res, next) => {
    pool.connect(function (err, client, done) {
        if (err) {
            console.log("Can not connect to the DB" + err);
        }
        client.query('SELECT * FROM srt_final WHERE info_init @> \'{"subscriber":"999999"}\' ORDER BY id DESC LIMIT 20', function (err, result) {
             done();
             if (err) {
                 console.log(err);
                 res.status(400).send(err);
             }
             var osaka = result.rows;

                     res.render('index', {  srt: osaka });
        })

    })
 });

数据本身看起来像这样(大约 30 个值)。

    [
{"id":11653167,"info_init":
  {"date":"05.07.2018"},
   ....
  {"Time":"10:31:17"}
},
  ....
{"id":11653168,"info_init":
  {:},
    ......
  {:}
}
]

【问题讨论】:

    标签: json node.js express ejs


    【解决方案1】:

    也许有点太晚了,但我找到的解决方案效果不佳。我需要更简单的东西,而不是模板引擎或库。此外,在尝试从 Mongoose 响应生成表时,提到的 npm 包 html-tablify 对我不起作用。顺便说一句,对不起我的英语不好。

    const row = html => `<tr>\n${html}</tr>\n`,
          heading = object => row(Object.keys(object).reduce((html, heading) => (html + `<th>${heading}</th>`), '')),
          datarow = object => row(Object.values(object).reduce((html, value) => (html + `<td>${value}</td>`), ''));
                                   
    function htmlTable(dataList) {
      return `<table>
                ${heading(dataList[0])}
                ${dataList.reduce((html, object) => (html + datarow(object)), '')}
              </table>`
    }
    
    const set = [
      {_id: 1234,
        usuario: 'user1',
        clave: 'pass1' },
      {_id: 12345,
        usuario: 'user2',
        clave: 'asdas' },
      {_id: 12357,
        usuario: 'user3',
        clave: 'asdasd' },
      {_id: 12376,
        usuario: 'user5',
        clave: 'asdasd' }
    ];
    
    htmlTable(set)
    

    输出:

    <table>
      <tr>
        <th>_id</th>
        <th>usuario</th>
        <th>clave</th>
      </tr>   
      <tr>
         <td>123</td>
         <td>xD</td>
         <td>asd</td>
      </tr>
      <tr>
         <td>123</td>
         <td>xD</td>
         <td>asd</td>
      </tr>
      <tr>
         <td>123</td>
         <td>xD</td>
         <td>asd</td>
      </tr>
      <tr>
         <td>123</td>
         <td>xD</td>
         <td>asd</td>
      </tr>
    </table>
    

    它是如何工作的......它实际上非常简单。 row 函数将一些值包装在标签内。 另一方面,heading 获取一个对象并根据对象自己的键创建表标题 html。 datarow,取一个对象,生成该行的所有单元格 标题和数据行函数都使用行函数返回行 html 代码。 htmlTable 函数接收对象列表,并返回完整表的 html 代码。

    通过一些调整,可以轻松添加标记格式、属性和样式。

    【讨论】:

      【解决方案2】:

      使用 html-tablify

      https://www.npmjs.com/package/html-tablify

      我将从 json 创建 html 表

      【讨论】:

        【解决方案3】:

        参考:How to create HTML table based on JSON

         var html = '<table class="table table-striped">';
            html += '<tr>';
            var flag = 0;
            $.each(data[0], function(index, value){
                html += '<th>'+index+'</th>';
            });
            html += '</tr>';
             $.each(data, function(index, value){
                 html += '<tr>';
                $.each(value, function(index2, value2){
                    html += '<td>'+value2+'</td>';
                });
                html += '<tr>';
             });
             html += '</table>';
             $('body').html(html);
        

        【讨论】:

        • 感谢您的回答,但在我使用此示例的情况下,我得到了以下结果: id info_init info_final state 12293245 [object Object] [object Object] 1 12291387 [object Object] [object Object ] 1
        • 参考:我创建了一个示例embed.plnkr.co/apjw1FF4Qu3yc1B3bSb6,因为您的对象在键“info_init”中有一些嵌套数据
        【解决方案4】:

        这不是NodeJS相关的问题,您可以查看html table如何在html中制作表格。然后通过nodejs更好地渲染动态内容是使用像ejs这样的视图引擎。

        【讨论】:

        • 你能告诉我如何带出所有“info_init”的内容吗?
        • info_init 是什么意思?
        • [ {"id":11653167,"info_init": {"date":"05.07.2018"}, .... {"Time":"10:31:17"} } , .... {"id":11653168,"info_init": {:}, ...... {:} } ]
        • 即只用“info_init”内容填充表格
        • 你使用任何寺庙引擎
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-26
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        相关资源
        最近更新 更多