Transform JSON To HTML Using JSON Templates - json2html.js

Transform JSON To HTML Using JSON Templates - json2html.js
File Size: 24.5 KB
Views Total: 3732
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A fast, convenient JavaScript JSON to HTML library that transforms JSON objects into HTML using JSON templates. Works with Vanilla JavaScript, jQuery and Node.js.

How to use it:

1. Load the json2html.js library and jQuery (OPTIONAL) in the HTML document.

<!-- jQuery -->
<script src="/path/to/cdn/jquery.min.js"></script>
<!-- Json2html -->
<script src="./json2html.js"></script>

2. Prepare your JSON data to be renderes as HTML.

var myData = [
    {'value':10,'label':'Day 1'},
    {'value':5,'label':'Day 2'},
    {'value':15,'label':'Day 3'},
    {'value':4,'label':'Day 4'},
    {'value':5,'label':'Day 5'}
];

3. Define the JSON template as follows:

let template = {'<>':'div','html':'${title} ${year}'};

4. Transforms the JSON into HTML based on the template you defined.

// Vanila JS 
document.write( json2html.render(data,template) );

// jQuery
$(function(){
  $(SELECTOR).json2html(data,template);
});

5. The plugin also supports event handlers based on jquery's on method.

{"<>":"li","id":"${id}","html":[
  {"<>":"span","html":"${name} ${year}"}
],"onclick":funciton(e){
  alert("You just clicked " + e.obj.name);
}}; 

Changelog:

2021-05-20

  • Fixed onready duplicate trigger issue

v2.0.0 (2021-03-31)

  • Added obj reserved attribute to templates for specifying data objects to render (html elements and components)
  • Added html blocks to map data to blocks of templates
  • Added automated testing with mocha

v1.4.1 (2020-04-10)

  • Updated jQuery Events

v1.4.0 (2020-03-02)

  • Merged jQuery into master json2html.js and added check for jQuery.

This awesome jQuery plugin is developed by moappi. For more Advanced Usages, please check the demo page or visit the official website.