Overview

json2html is a javascript HTML templating library used to transform JSON objects into HTML using a another user specified JSON template, which we call transforms. Use with

  • Native Javascript using the core library
  • jQuery as jquery plug-in,extending the core library to include jquery events
  • Node.js as node.js package, used on a node.js web server

Each wrapper uses the same transform, allowing for one transform to be written that can be run on either the web client (browser) or web server

Features

json2html uses JSON templates, which we call transforms, to convert your source JSON objects to HTML. So what makes these transforms special?

  • Unlike an HTML templates, JSON transforms can be read natively within the browser (and server) and don't require any special script wrappers
  • One template for both the client and server
  • Embed events directly into your transforms (with the jquery plugin)
  • No need to learn new syntax, use inline javascript functions for complex logic
Transforms

Transforms are simply JSON templates that are used to convert the source JSON objects into HTML. Each transform specifies a hierarchy of DOM elements (div, span, li, etc..) with name value pairs, or attributes, of the transform object represent the attributes found on the DOM HTML element, with the exception the following reserved attribute names

  • <> specifies the type of DOM element (div, span etc..)
  • html specifies the innerHTML this DOM element will contain inlcuding all DOM children
  • children (deprecated)
  • tag (deprecated)
var transform = {'<>':'li','html':[
                    {'<>':'span','html':'${name} (${age})'}
                ]};
    
var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];
    
$('ul').json2html(data,transform);
<ul id="list">
    <li>
        <span>Bob (40)</span>
    </li>
    <li>
        <span>Frank (15)</span>
    </li>
    <li>
        <span>Bill (65)</span>
    </li>
    <li>
        <span>Robert (24)</span>
    </li>
</ul>

Usage

JSON2HTML can be used on both the browser and the server.

Native & Node.js

Using the following on the browser or with Node.js

json2html.transform(source, transform)
  • source object (or array) of JSON object(s) to transform
  • transform object (or array) of JSON transform object(s)
  • output HTML string
var html = json2html.transform([{'s':'json2html'},{'s':'is'},{'s':'awesome'}],{'<>':'li','html':'${s}'});
jQuery

Using this along with a jQuery selector you can attach the transform to a DOM object along with jQuery events by embedding event attributes within the transform (see the Events Attributes section)

$(selector).json2html(source, transform, [options])
  • source object (or array) of JSON object(s) to transform
  • transform object (or array) of JSON transform object(s)
  • [options] an optional options object with the folowing variables
    • eventData user specified object that will be passed to a DOM event (onclick, onmouseover etc..), used to help keep context; default is an empty object
    • append [true/false] elements will be appended to the existing elements in the source object
    • prepend [true/false] elements will be pre-pended to the existing elements in the source object
    • replace [true/false] elements will be replace the elements in the source object
  • output jquery DOM element(s)
$('ul').json2html([{'s':'json2html'},{'s':'is'},{'s':'awesome'}],{'<>':'li','html':'${s}'});

Also you can transform using directly to an HTML string, note that jQuery events won't be attached (unless used within an inline function)

$.json2html(source, transform, [options])
  • source object (or array) of JSON object(s) to transform
  • transform object (or array) of JSON transform object(s)
  • [options] an optional options object with the folowing variables
    • eventData user specified object that will be passed to a DOM event (onclick, onmouseover etc..), used to help keep context; default is an empty object
  • output HTML string
var html = $.json2html([{'s':'json2html'},{'s':'is'},{'s':'awesome'},{'<>':'li','html':'${s}'});

Attributes

Transforms are made up of either a JSON objects or arrays of JSON objects. Each of these JSON objects contains a variety of attributes that are mapped to the newly created DOM element. Some of these attributes are reserved while others are simply mapped to a DOM element attribute. The following describes these attributes and how data is mapped to each attribute.

<>

The first required step in creating a transform is specifying the '<>' attribute for each object within the transform. This will specify the HTML element (eg: div,a,p,table etc..) that you wish to be created. Note that the 'tag' attribute can also be used in support of legacy transforms

{'<>':'div'}
<div></div>
html

The reserved html attribute is used to specify the inner html of the DOM element. As with any other attribute you can specify a literal string, use short hand notation or an inline function (see Assignment for more details). In addition you can also specify an array of children transforms that will belong to this DOM element.

{'<>':'div','html':[
    {'<>':'span','html':'1'},
    {'<>':'span','html':'2'}
]} 
<div>
    <span>1</span>
    <span>2</span>
</div> 

Note that there are no limits to the number of children that a transform object may have or on the number of nested levels of children.

{'<>':'div','html':[
    {'<>':'div','html':[
        {'<>':'span','html':'final'}
    ]
]} 
<div>
    <div>
        <span>final</span>
    </div>
</div>

Use of an inline function can be used to return and html string or from another json2html call. This may include inserting html using another core json2html.transform call (or jquery $.json2html call).

var data = [
    {'id':'100','children':[
        {'name':'this'},
        {'name':'is'},
        {'name':'great!'}
    ]},
    {'id':'101','children':[
        {'name':'this'},
        {'name':'is'},
        {'name':'amazing!'}
    ]}
];

var transforms = {
    'parent': {'<>':'div','id':'${id}','html':function(){
        return $.json2html(
                    this.children,
                    transforms.child));
    },
    'child':{'<>':'span','html':'${name}'}
};

$('ul').json2html(data,transforms.parent);
<ul>
<li id=100>
    <span>this</span>
    <span>is</span>
    <span>great!</span>
</li>
<li id=101>
    <span>this</span>
    <span>is</span>
    <span>amazing!</span>
</li>
DOM Attributes

All DOM attributes are supported, this includes standard id, class etc.. as well as user defined attributes.

{'<>':'div','id':'id-123','class':'red','data-id':'123','html':'inner html'}
<div id='id-123' class='red' data-id='123' >inner html</div>
Events

Using the jQuery wrapper allows for jQuery events to be embedded within a transform. These events will be automatically attached when the transform is applied to the DOM using a jQuery selector eg. $('ul').json2html(..))

Event attributes (onclick, onfocus, onmouseout etc..) are created by adding an event handler to the DOM element using jquery, each handler requires an inline function to evaulate when the event is triggered. Supported events include all jQuery events that can be attached to a DOM element, simply add the 'on' prefix to the following found on the jQuery events page

Here's a partial list of the supported events, with the required 'on' prefix added

  • onclick
  • onblur
  • ondblclick
  • ondie
  • onerror
  • onchange
  • onhover
  • onfocus
  • etc..

{'<>':'button','onclick':function(e){
    //e.event : the jQuery event
    //e.data  : user specified data from the the json2html options variable eventData (see Usage)
    //e.obj   : the source object that we are transforming
    //e.index : the index of the array in which the source object was found
}}
{'<>':'button','html':'click me','onclick':function(e){
    console.log(e.obj.name);
}
<button>click me</button>

In addition the source jQuery element that called the event can also be accessed using $(this); which is the same as referencing e.event.target in the example above

{'<>':'span','onclick':function(){
    $(this).hide();
}
<span>click me</span>

Assignment

To assign data from your source data JSON object to your transform you'll need to use one of the following assignment methods

Literals

You can assign literal text to any of the DOM attributes of a transform.

{'<>':'div','id':'some-div','class':'some-class','html':'some stuff'}
<div id='some-div' class='some-class' >some stuff</div>
Shorthand Notation

Shorthand notation is the easiest way to map data from the source JSON object, simply specify the variable in the format ${varname} where varname is the variable name within the source JSON data object. Data from the JSON object will then be inserted into that attribute during runtime. Note that any number of variables as well as literal text can be found within the property of a transform object.

{'<>':'div','id':'${id}','class':'${highlight}','html':'${title} is amazing!'}
<div id='1' class='red'>Fast and the Furious: Part 2 is amazing!</div>

The above example will map the source JSON field 'title' to the inner html of the div (plus some other text), it will also place the variable 'highlight' for the class name and 'id' for the id of the DOM object. For a source JSON object with the name source, this would be the same as writing data[x].title. Note that if the field is not named, but rather, it is referenced by an index the following can be used:

{'<>':'div','html':'${movie.0.title} is amazing!'}
<div>Fast and the Furious is amazing!</div>

The above example will map the source JSON field movie [0].title to the inner html of the div. This would be the same as writing data[x].movie[0].title

Inline Function

Inline functions can be used to embed logic to assign property values to any DOM attributes including the reserved html attribute.

{'<>':'div','class':function(){return('red');},'html':'this is in red'}
<div class='red'>this is in red</div>

json2html will pass the source JSON object to the function as a parameter as well as the index in the array of objects that it was found, allowing for the function to process the fields in any manner.

{'<>':'div','html':function(obj,index){
                        return(obj.title + ': ' + obj.date);
                    }}
<div>Fast and the Furious : May 10th 2011</div>

Alternatively, the source JSON object can also be referenced using the key word 'this'

{'<>':'div','html':function(){return(this.title + ': ' + this.date);}}
<div>Fast and the Furious : May 10th 2011</div>

The above example could also be done using short-hand notation, as follows

{'<>':'div','html':'${title} : ${date}'}
<div>Fast and the Furious : May 10th 2011</div>

When using an inline function you can also reference the index of the object you're transforming

{'<>':'li','html':function(obj,index){
                        return(index + ". " + obj.title);
                    }}
<ul>
    <li>0. Fast and the Furious</li>
    <li>1. The Avengers</li>
    <li>2. Iron Man</li>
</ul>