Convert json to html table in node JS
1 min readNov 20, 2020
Given a JSON. how would you convert it to an HTML Table?
I looked up and found that node-json2html allows me to, there however wasn’t precise documentation around how to create an HTML Table using this.
So — say, if this is my JSON
[
{
"App Name": "Yahoo",
"Accessibility": 94,
"Best Practices": 93,
"SEO": 90,
"Performance": 54
},
{
"App Name": "Google",
"Accessibility": 89,
"Best Practices": 86,
"SEO": 80,
"Performance": 41
},
{
"App Name": "Guardian UK",
"Accessibility": 89,
"Best Practices": 86,
"SEO": 80,
"Performance": 41
}
]
First thing I need is to define templates looking up examples from node-json2HTML
let template_table_header = {
"<>": "tr", "html": [
{"<>": "th", "html": "App Name"},
{"<>": "th", "html": "Accessibility %"},
{"<>": "th", "html": "Best Practices %"},
{"<>": "th", "html": "SEO %"},
{"<>": "th", "html": "Performance %"}
]
}
let template_table_body = {
"<>": "tr", "html": [
{"<>": "td", "html": "${App Name}"},
{"<>": "td", "html": "${Accessibility}"},
{"<>": "td", "html": "${Best Practices}"},
{"<>": "td", "html": "${SEO}"},
{"<>": "td", "html": "${Performance}"}
]
}
Thereupon it is pretty much building the HTML table as we wish.
note that if you need any attributes in your table cells, rows etc. you could change the template like this
{"<>": "td data-value='${SEO}'", "html": "${SEO}"},
This is my full Node JS script for reference
Hope you find this useful.