Display JSON data in HTML with one function call.
This article is meant for someone who is looking for a quick solution on:
1) How to fetch data from an API?
2) How to convert fetched data from an API into JSON?
3) How to display JSON data in HTML with one function call?
Whenever we think of displaying some JSON data into HTML we tend to turn our heads towards JavaScript. Since JavaScript is meant to deal with the HTML content of a document.
Further, when we need to display some data in a document using JavaScript we start thinking of client-side scripting involving two major elements like:
1) DOM methods
2) jQuery
Instead of that a better way is switch to server-side scripting involving Node.js
Why so?
Because Node.js comes with a package manager called “npm”. And here’s the catch to display your JSON data in HTML with one function call the create-html function (package).
Let’s see how this one function call can make all our hustle easier to create the content of an HTML file.
Examples
A simple example that creates an HTML file with the title example
:
var html = createHTML({
title: 'example'
})
Example using all options:
var html = createHTML({
title: 'example',
script: 'example.js',
scriptAsync: true,
css: 'example.css',
lang: 'en',
dir: 'rtl',
head: '<meta name="description" content="example">',
body: '<p>example</p>',
favicon: 'favicon.png'
})
You can read about more options available in create-html.
Now first let’s see how to fetch data from an API:
fetch('http://example.com')
.then(response=>{
var data = response;
return data.json(); //Parsing the data into json
})
You can read more about API here: fetch
The second step is to fetch some content from the API and then display it in an HTML table:
.then(contents=>{
console.log("Iterating through the 'result' array of objects to be displayed in table");
_.forEach(contents.result,function(value,key){
tableHtml=tableHtml+'<tr>'+
'<td>'+value.movie_names+'</td>'+
'</tr>';
})
var html = createHTML({
title: "Table - " + (new Date().toUTCString()),
scriptAsync: true,
css: '',
script: '',
lang: 'en',
dir: 'ltr',
head: '<meta charset="utf-8">'+
'<meta name="description" content="">'+
'<meta name="author" content="">'+
body: '<main role="main" class="container">'+
'<h1 class="mt-5">'+ 'JSON data in HTML'+'</h1>'+
'<table class="table table-hover">'+
'<thead>'+
//Add headers
'<th scope="col">Movie Name</th>'+
'</thead>'+
'<tbody>'+
//Add data to be displayed in the table
tableHtml +
'</tbody>'+
'</table>'+
'</main>'
})
If you want to know how to run a node.js script which will extract the data and print response from an API to an HTML report (table) you can refer to this repository/project.