开发者

Automatically generate HTML from JSON

I am working on a template system. I imagine that as a regular user you can create a. json file, and based on that file the system will automatically generate html. I am fairly lost with how to approach it. Maybe I could create a recursive loop that runs through all objects and then.... (well I'm lost).

An example of how the JSON could look: http://pastebin.com/cJ3开发者_如何学C76fiF.

How the generated HTML should look like: http://pastebin.com/e4EytHm1.


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'}]
  }

};


jQote2 is an excellent javascript templating plugin, which should be atleast a good benchmark. It parses JSON into HTML templates in a very handy way. http://aefxx.com/jquery-plugins/jqote2/


@topherg

  • It is faster to bind obj to parent earlier - direct after createElement.

  • When you come to object.children you should check:

    if(object.children.constructor===Array){
      for(var i=0;i<object.children.length;i++)
         createElementsFromJSON(object.children[i],obj);
    }else{
       createElementsFromJSON(object.children,obj);
    }
    

    Otherwise no array will be parsed.

  • SetAttribute is slow but sometimes you need it for (name,item*,data-*,rel,objekt,param,loop,datetime,style[if you don't want to parse an additional object],colspan,...). Direct Set Attribute (element.style.width="100px";) is 88 times faster (jsPerf).

To create ONE DOM element is faster than innerHTML. Building a DOM tree directly, takes double time of innerHTML. Even innerHTML is very fast that kind of DOM parsing is still fast too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜