Automatically generate HTML from JSON Automatically generate HTML from JSON json json

Automatically generate HTML from JSON


http://www.json2html.com/

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


probably a bit late, i was gonna do something similar, and came across this thread, but have some code, the callback function is called from an XHR object which gets data from the currently static file "response.json"

function callback(req){    var response = eval("("+req.responseText+")");    response = response.response;    createElementsFromJSON(response, document.body);}function createElementsFromJSON(json, parent){    for(var i in json)    {        var object = json[i];        var obj = document.createElement(object.element);        for(var tag in object)            if (tag!="children"&&tag!="element")                obj.setAttribute(tag, object[tag]);        parent.appendChild(obj);        if (typeof(object.children)=="object")            createElementsFromJSON(object.children, obj);    }}

JSON:

{    "response":    [        {            "element":"div",            "id":"james",            "children":            [                {                    "element":"h1",                    "id":"bob",                    "innerHTML":"bobs content",                },                {                    "element":"h2",                    "id":"rob",                    "innerHTML":"robs content",                },                {                    "element":"p",                    "innerHTML":"some random text",                },            ],        },        {            "element":"div",            "id":"alex",            "innerHTML":"this is a test message in a div box",        },    ]}


I have done a humble attempt for my own project to dynamically generate html content through JSON. You can try the fiddle here. You are welcome to fork it since the JSON format is different.

Sample JSON format would look as below.

var innerhtml = {  type: 'b',  content: ['This is BOLD text.', {    type: 'i',    content: ' Italics came from Italy? Its 35px and bold too.',    style: 'font-size:35px;'  }]};var htmlArr = {  type: 'div',  content: {    type: 'p',    content: ['Simple text with no formatting.', innerhtml, {type : 'img', src : '//www.gravatar.com/avatar/476914f28548ce41b3b7b2c5987720a9/?default=&s=64'}]  }};