Transform JSON to HTML

A new kind of client side templating

json2html is an open source jQuery plug-in that relies on JSON transforms to convert JSON objects to HTML.

  • 100% client no server code required
  • browser readable no template compiling
  • jQuery events seemless integration
  • inline functions to easily manipulate data

Note this plug-in is currently in beta mode, any suggestions are welcome Contact

Try it out!

[{'a':'json2html','b':'so easy!'},
 {'a':'jquery','b':'the best!'}]
Data
{'tag':'li','html':'${a} is ${b}'}
Transform
	
    HTML

    Having a hard time figuring out how to create a transform?
    Use the transform builder below to help encode a HTML markup template into a json transform.

    HTML Template

    JSON Transform

    • Version 3.0

      • Altered short-hand notation from '.' to '${varname}'
      • Added tokenization to look for multiple variables within transform
    • Version 2.5

      • Performance Tuning (40% improvement)
      • Removed auto unstructured list creation
    • Version 2.3

      • Removed extra div's added around children and li elements
      • Added ability to convert one json element to a non li list
    • Version 2.0

      • Fixed issue with events: events now handled by inline functions mapped to the correct jquery event handler
      • Added options parameter, including the prepend in the options and event data (to help pass context to an event)
      • Added inline function as source for children attribute; allows for json2html to be called recursively for children
    • Version 1.1

      • Attribute value that is mapped to the source object MUST have the reserved character '.' as the FIRST character; otherwise value will be read as a litteral
    • Version 1.0

      • Source JSON is required to be in an array format
      • Source JSON will only render one level deep, any sub arrays found in source objects will be ignored
      • Top level output is limited to an unstructured list
      • Extra divs added when children are specified

    License

    Copyright (c) 2011 Crystalline Technologies Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Usage (for Version 3.0)

    jQuery.json2html(source, transform, [options])

    • source object (or array) of JSON object(s) to transform
    • transform object (or array) of JSON transform object(s)
    • options [optional] options object with the folowing variables
      • eventData user specified object that will be passed to a DOM event (onclick, onmouseover etc..), see Event Attributes; used to help keep context; default is null
      • prepend elements will be prepended to the original list, default is to append elements to the end of the list (false)

    The $.json2html() function is used to transform a JSON object (or array of objects) into HTML using the provided JSON transform. A transform is made up of a JSON object (or array) that will be used to convert the source JSON object to HTML. Below is an example of a transform object that creates two html elements for every source object, a span and a div.

    var transform = [{tag:'span',html:'${pubDate}'},{tag:'div',html:'some text'}]; 
    

    The transform specifies a hierarchy of DOM elements (div, span, etc..). 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:

    • tag [string] specifies the DOM element name for this object (eg div, span, img, a, etc..)
    • html [string or inline function] specifies the inner html of this DOM element (can be a function or a string value)
    • children [array or inline function] specifies an array of transform objects that will be appended as children to this element. Note that if an inline function is used an array of DOM elements is expected and will be appended to the parent DOM element.

    Standard Attributes

    There are three ways to map data to a DOM object attribute and the reserved 'html' attribute:

    • Use literal text: note that the text MUST not be wrapped in the reserved ${} character combination
      {tag:'div',id:'myDiv',class:'myClass',html:'This is my new div!'}
      
      <div id='myDiv' class='myClass'>This is my new div!</div>
      
    • Using shorthand notation: the easiest way to map data from the source JSON object is to 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.
      {tag:'div',html:'${title} is amazing!'}
      
      <div>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. For a source JSON object with the name source, this would be the same as writing source[x].title. Note that if the field is not named, but rather, it is referenced by an index the following can be used:
      {tag:'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. For a source JSON object with the name source, this would be the same as writing source[x].movie[0].title
    • Use an inline function: Property values can be specified using an inline function that returns a string.
      {tag:'div',html:function(obj){return('This is the innerHTML of the div');}}
      
      <div>This is the innerHTML of the div</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:
      {tag:'div',html:function(obj,index){return(obj.title + ': ' + obj.date);}}
      
      <div>Fast and the Furious : May 10th 2011</div>
      
      note that the above example could also be done using short-hand notation:
      {tag:'div',html:'${title} : ${date}'}
      
      <div>Fast and the Furious : May 10th 2011</div>
      

    Children Attribute

    The reserved children attribute is used to specify the associated children of this new DOM element. Children are added to the transform object by specifying an array of JSON transform objects under the 'children' attribute. Children can be added in one of two ways:

    • Specifying an array of transform objects that are added as the attribute value to specify the children of the newly create DOM element
      {tag:'div',children:[
       {tag:'span',html:'1'},
       {tag:'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.
      {tag:'div',children:[
       {tag:'div',children:[
        {tag:'span',html:'final'}
       ]
      ]} 
      
      <div>
       <div>
        <span>final</span>
       </div>
      </div>
      
    • Use of an inline function which returns an array of DOM objects: an inline function can be used to return an array of DOM objects (note that it MUST be in the form of an array) that will be appended to the resulting DOM parent. This may include inserting children using another json2html call.
      {tag:'div',children:function(obj){return($.json2html(obj.children,transform));}}
      
      <div>
       <span>child1</span>
       <span>child2</span>
      </div>
      

    Event Attributes

    DOM even attributes (onclick, onmouseover, onmouseout etc..) are created by adding an event handler to the DOM element using jquery. Note that these attributes require an inline function as the value. The parameter passed to this inline function contains the following fields:

    • event the jquery event
    • data user specified data from the the json2html options variable eventData
    • obj the source object that we are transforming
    • index the index of the array in which this object was found
    {tag:'span',onclick:function(e){alert(e.obj.name);}
    

    Google Calendar Feed

    In this example the google development calendar is loaded as a JSON object and rendered into a list using json2html. Note that there are two functions not shown in the code below: getLink() is used to get the hyper link of the calendar object and formatGCalTime() is a google function to format the calendar time into something more useful.

    http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json-in-script&callback=insertAgenda&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true

    var transform =
    [{tag:'li',class:'googleCalendarEntry',children:[
      {tag:'a',href:function(obj){return(getLink(obj));},children:[
       {"tag":"span","html":"${title.$t}"}
      ]},
      {tag:'span',html:'-'},
      {tag:'span',html:function(obj) {return(formatGCalTime(obj.gd$when[0].startTime));}}
     ]}
    ];
    
    $('#googleFeed').json2html(root.feed.entry,transform);
    
    View Example

      Yahoo Sports Feed

      In this example we use a yahoo pipe to return the latest sports news from Yahoo as JSON, which in turns is rendered into html using json2html.

      http://pipes.yahoo.com/pipes/pipe.run?_id=5f533fd241bcabc46ce55a783f2eba84&_render=json

      var transform = [
       {tag:'li',class:'yahooSportsEntry', children:[
        {tag:'div',class:'thumbnail',style:function(obj){if(obj['media:content']==undefined) return('display:none');},'children':[
         {tag:'img',src:'.media:content.url',align:'left'}
        ]},
        {tag:'div',class:'text',children:[
         {tag:'a',href:'${link}',children:[
          {tag:'span',html:'${title}'}
         ]},
         {tag:'span',html:'${pubDate}'},
         {tag:'div',class:'description',html:'${description}'}
        ]}
       ]}
      ];
      
      $('#yahooFeed').json2html(yahooPipe,transform);
      
      View Example

        Twitter Feed

        In this example we use the tweets from Project_Climb to return a JSON encoded list of twitter feeds from Twitter which is turn is rendered into html using json2html.

        http://twitter.com/status/user_timeline/project_climb.json?count=10&callback=showFeed

        var transform = [
         {tag:'li',class:'twitterFeed',children:[
          {tag:'div',class:'image',children:[
           {tag:'img',src:'${user.profile_image_url}',align:'left'}
          ]},
          {tag:'div',class:'user',children:[
           {"tag":"a","href":'http://twitter.com/#!/${user.screen_name}',"html":"${user.screen_name}"},
           {tag:'span',html:'${user.name}'}
          ]},
          {tag:'div',class:'text',children:[
           {tag:'span',html:'${text}'}
          ]},
          {tag:'div',class:'date',children:[
           {tag:'span',html:'${created_at}'},
           {tag:'div',class:'source',html:function(obj){if(obj.source != null) return('Source: ' + obj.source); else return('');}}
          ]}
         ]}
        ];
        
        $('#twitterFeed').json2html(twitterFeed,transform);
        
        View Example

          Bar Chart

          In this example we create a JSON object with data we want to chart, then using a transform, we turn it into a simple bar chart.

          var chartData = { groups:
            [{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'}
           ]};
          
          var transforms = {
           barChart: [
            {tag:'ul',class:'barChart',children:function(obj) {return($.json2html(obj.groups,transforms.group));}}
           ],
           group: [
            {tag:'li',class:'group',children:[
             {tag:'div',class:'bar',style:'height:${value}px;'},
             {tag:'div',class:'label',html:'${label}'}
            ]}
           ]
          };
          
          $('#chart').json2html(chartData, transforms.barChart);
          
          View Example