Transform JSON To HTML Using JSON Templates - json2html.js

Transform JSON To HTML Using JSON Templates - json2html.js
File Size: 17.8 KB
Views Total:
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 wrapper in the HTML document.

<!-- jQuery -->
<script src="/path/to/cdn/jquery.min.js"></script>
<!-- Json2html -->
<script src="./json2html.js"></script>
<script src="./jquery.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:

var myTemplate = {
    "bar": [
      {"<>":"li","class":"group","title":"${label}","html":[
        {"<>":"div","class":"bar","style":function(){
          return('height:' + this.value*10 + 'px;');
        }},
        {"<>":"div","class":"label","text":"${label}"}
      ],"onclick":funciton(e){
        // do something
      }}
    ]
};

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

$(function(){
  $(SELECTOR).json2html(data, myTemplate.bar);
});

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

$(function(){
  $(SELECTOR).json2html(data, myTemplate.bar);
});

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