Aldem
Aldem

Reputation: 47

How to build a dynamic html table from json data using node js?

There is a small project at nodejs + express + postgres for self-education. By requesting Postgres I get data in json format, then the data on the express tools is rendered to the ejs template. The very question is how do I add this json to a dynamic table in html.

The request to the database looks like this

    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 });
        })

    })
 });

The data itself looks like this (about 30 values).

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

Upvotes: 0

Views: 16453

Answers (4)

Emilio Grisolía
Emilio Grisolía

Reputation: 1203

A little too late maybe, but the solutions I found didn't work quite well. I needed something simpler, not a template engine or a lib. Also, the mentioned npm package, html-tablify, didnt work for me when trying to generate a table from a Mongoose response. Btw, sorry for my bad english.

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)

Output:

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

How does it works... it is actually pretty simple. The row function wraps some value inside a tag. heading, on the other side, takes an object and creates the table heading html based on the object's own keys. datarow, takes an object, and genereate all the cells of the row Both heading and datarow functions returns a row html code by using the row function. htmlTable function receives a list of objects, and just returns the full table's html code.

With a few tweaks, markup formatting, attributes and styles can be easily added.

Upvotes: 2

toyeca
toyeca

Reputation: 169

Use html-tablify

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

I will create html table from json

Upvotes: 0

Senthil
Senthil

Reputation: 2246

Ref: 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);

Upvotes: 0

Osman Goni Nahid
Osman Goni Nahid

Reputation: 1279

It's not about NodeJS related question, you can look into html table how to make table in html. Then render dynamic contents by nodejs better is use a view engine like ejs.

Upvotes: 0

Related Questions