28

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/cJ376fiF.

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
Mikkel
  • 707
  • 4
  • 8
  • 15
  • 2
    Me as a user would rather write HTML than write json that will describe how a web page should look and what it will have. Also, have you thought about how you will handle styling? – LoveGandhi Apr 19 '11 at 02:09
  • 1
    Is there a reason you can't use jQuery and its template plugin? – Phil.Wheeler Apr 19 '11 at 02:09
  • 2
    Have you really saved yourself much between JSON and HTML? The `label` and `fieldset` seem to imply that your *regular user* would have to have some knowledge of HTML elements. – Jason McCreary Apr 19 '11 at 02:10
  • I partly agree in what you guys are saying, but is this case, json is the best solution for the user (at least i believe so). ;) – Mikkel Apr 19 '11 at 02:13
  • @Phil.Wheeler Haven't heard of it, i'm gonna take a look right now ;) – Mikkel Apr 19 '11 at 02:17
  • Sounds like you are trying to reinvent HAML – Zepplock Apr 19 '11 at 02:22
  • 1
    I don't understand why you are generating a format that is different to what you want. JSON is good for sending *data* to several (usually hetergeneous) clients. But if the client wants HTML, just send HTML. You can also format your data as XML and then use XSLT to convert it to HTML (on the server preferably, but it can be on the client) or any other markup for different clients. – RobG Apr 19 '11 at 02:45
  • 1
    Good point. I'm convinced , i'm gonna use XML or just HTML. Thanks everybody ;) – Mikkel Apr 19 '11 at 02:49
  • @Mikkel if ya want to use XML, for XHR you could use .responseXML, but using plain html would be easier. If you are planning on using scripts, then you can use a checker to find script elements, then re-create them in the header to execute them. – topherg Nov 14 '11 at 02:03

5 Answers5

16

http://www.json2html.com/

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

Bernicc
  • 636
  • 6
  • 14
5

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",
        },
    ]
}
topherg
  • 4,203
  • 4
  • 37
  • 72
2

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

};
1

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/

Marcus
  • 5,083
  • 3
  • 32
  • 39
  • it does seem logical, i think he just wants to build one himself – topherg Oct 27 '11 at 11:44
  • That's the image I got too. Still I would use some existing solutions first to see the good/bad parts. And go through the code of some of the better solutions, especially if a bit lost about how to implement similar system. – Marcus Oct 27 '11 at 14:29
  • I did it just [here](http://stackoverflow.com/q/9652420/817152) akin to a question at stackOverFlow. It's pure javascript as asked. – B.F. Aug 28 '14 at 16:58
0

@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.

B.F.
  • 477
  • 6
  • 9