Node.js Project to Convert JSON Objects to HTML Markup Using node-json2html Library in Javascript Full Tutorial For Beginners

Node.js Project to Convert JSON Objects to HTML Markup Using node-json2html Library in Javascript Full Tutorial For Beginners

 

Welcome folks today in this blog post we will be converting json objects to html template using node-json2html Library in javascript. All the full source code of the application is given below.

 

 

 

Installation

 

 

 

You can install this node-json2html library by issuing the npm command

 

npm i node-json2html

 

This will install this library inside your node.js project

 

Now make an index.js file and copy paste the following code

 

index.js

 

Usage

 

const json2html = require('node-json2html');
        
    let html = json2html.transform([{'male':'Bob','female':'Jane'},{'male':'Rick','female':'Ann'}],{"<>":"div","html":"${male} likes ${female}"});

 

 

 

 

 

Transform Template

 

let transform = 
 {"<>": "li", "id":"${id}", "html":[
    {"<>": "span", "text": "${name} (${year})"}
  ]};

 

 

Here inside this template we have the li tag and we have id parameter also. And inside the html attribute we have the text attribute

 

And then for this template we can provide the json data

See also  Javascript Program to Find Difference of Two Sets Data Structures in Browser Full Project For Beginners

 

let data = 
 {"id": 1123, "name": "Jack and Jill", "year":2001};

 

 

It will render out the below html

 

 

<li id="1123">
    <span>Jack and Jill (2001)</span>
</li>

 

 

Another Example

 

const json2html = require('node-json2html');
 
let template = {'<>':'div','html':'${title} ${year}'};
    
let data = [
    {"title":"Heat","year":"1995"},
    {"title":"Snatch","year":"2000"},
    {"title":"Up","year":"2009"},
    {"title":"Unforgiven","year":"1992"},
    {"title":"Amadeus","year":"1984"}
];
    
let html = json2html.transform(data,template);

console.log(html)

 

 

 

 

 

Using in Pure Javascript Browser Side

 

 

 

We can also use this library inside browser using javascript cdn

 

 

<script src="https://cdnjs.cloudflare.com/ajax/libs/json2html/1.4.0/json2html.min.js"></script>
 
<script>
    let template = {'<>':'div','html':'${title} ${year}'};
        
    let data = [
        {"title":"Heat","year":"1995"},
        {"title":"Snatch","year":"2000"},
        {"title":"Up","year":"2009"},
        {"title":"Unforgiven","year":"1992"},
        {"title":"Amadeus","year":"1984"}
    ];
    
    //native javascript
    document.write( json2html.transform(data,template) );
    
    //or with jQuery
    $("#result").json2html(data,template);
    
</script>

 

Leave a Reply