Transform JSON To HTML Using JSON Templates - json2html.js

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

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:

v2.2.2 (2022-04-09)

  • Added support for Typescript
  • Added support for spaces in json variable names for short hand notation
  • Fixed issue with ready event firing multiple times

v2.2.1 (2022-01-25)

  • Fixed issue with variable name starting with $

2021-11-04

  • Deprecated reserved 'obj' attribute and replaced with new '{}' attribute
  • Added support for multiple events per object (previously limited to 1 event per attribute)
  • Added experimental ES6 literal support
  • Updated examples to use new reserved {} attribute

2021-10-30

  • Multi events support & ES6

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.