1

I am trying to convert a JSON into an unordered list in jQuery.This is my JSON data.

var myJSON = "{name:\"Director\",children:[name:\"Exe Director1\",name:\"Exe Director2\",name:\"Exe Director3\",children:[name:\"Sub Director1\",name:\"Sub Director2\",name:\"Sub Director3\",children:[name:\"Cameraman 1\",name:\"Cameraman 2\"]]]}";

The expected output being

<ul>
    <li>Director
        <ul>
            <li>Exe Director 1</li>
            <li>Exe Director 2</li>
            <li>Exe Director 3
                <ul>
                    <li>Sub Director 1</li>
                    <li>Sub Director 2</li>
                    <li>Sub Director 3
                        <ul>
                            <li>Cameraman 1</li>
                            <li>Cameraman 2</li>
                        </ul>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

How do I go about with this!

Cheers,

3
  • stackoverflow.com/questions/9575267/… take a look at this one Commented Oct 4, 2012 at 15:30
  • Can this be achieved without using a plugin! :-) Commented Oct 4, 2012 at 16:55
  • Nope. Template API was once part of jQuery but is currently only available as plugin. Commented Oct 5, 2012 at 10:27

2 Answers 2

5

This is exactly what you need:

Use the jQuery template API. This was once part of jQuery but is currently only available as plugin. However, I think jQuery will adopt this or a similar technique again soon.

http://api.jquery.com/category/plugins/templates/

Its super easy to use:

$.tmpl("template", jsonObject)

Here a small basic template example:

$.tmpl(
    "<li><b>${Id}</b>${Name}</li>", 
    [{Id:1, Name:"Werner"}, {Id:2, Name:"Klaus"}]
);

This will result in the following jQuery HTML element that can be appended to anywhere:

  • 1 Werner
  • 2 Klaus
  • For your complex data, you can also iterate JSON sub objects using the "{{each}}" template notation. Here the code for your data and template:

    var data = {name:"Director",children:[{name:"Exe Director1"},{name:"Exe Director2"},{name:"Exe Director3", children:[{name:"Sub Director3_1"},{name:"Sub Director3_2"},{name:"Sub Director3_3",children:[{name:"Cameraman3_3_1"},{name:"Cameraman3_3_2"}]}]}]};
    
    var template = '\
        <ul>\
            <li>${name}\
                <ul>\
                    {{each(childindex, child) children}}\
                        <li>${child.name}\
                            <ul>\
                                {{each(child2index, child2) child.children}}\
                                    <li>${child2.name}</li>\
                                {{/each}}\
                            </ul>\
                        </li>\
                    {{/each}}\
                </ul>\
            </li>\
        </ul>\
    ';
    
    $('body').empty().append($.tmpl(template, data));
    

    Browsers Result:

    • Director
      • Exe Director1
      • Exe Director2
      • Exe Director3
        • Sub Director3_1
        • Sub Director3_2
        • Sub Director3_3
        • ...

    This can be tweaked to support full recursion by including nested templates... but im a lazy guy and the rest is todo for you.

    cheers, will

    Sign up to request clarification or add additional context in comments.

    4 Comments

    I would consider using another template engine, since jQuery Templates was still in beta and isn't being maintained anymore.
    jsRender would be a good alternative for any new development. jQuery templates has been discontinued. As mentioned by Klaster_1 and as per github.com/jquery/jquery-tmpl#readme Note: The jQuery team has decided not to take this plugin past beta. It is no longer being actively developed or maintained. See vBeta1.0.0 tag for released beta version. Requires jQuery version 1.4.2. Any open issues will not be worked on and remain open.
    Okay, the JsRender Syntax is nearly 100% identically. ill update my post as soon as i checked JsRender out.
    Quick note - it's probably a good time to update your example since it still floats in Google. Here's JS Render - github.com/borismoore/jsrender
    1

    You can use recursive function as follows. Everytime the function is called it returns a "UL", along with its child "LI".

    function generateMenu(data) {
    
        var ul = $("<ul>");
    
            $(data).each(function (i, dir) {
                 var li = $('<li>' + dir.name + '</li>');
                 ul.append(li);
    
                if (dir.children != null && dir.children.length > 0) {
                    li.append(generateMenu(dir.children));
                }
    
            });
    
        return ul;
    };
    

    Use it as :

    $("#some-div").append(generateMenu(myJsonData));

    The Json is,

    var myJsonData = JSON.parse('{"name": "Director","children": [{ "name": "Exe Director1" },{ "name": "Exe Director2" },{"name": "Exe Director3","children": [{ "name": "Sub Director1" },{ "name": "Sub Director2" },{"name": "Sub Director3","children": [{ "name": "Cameraman 1" },{ "name": "Cameraman 2" }]}]}]}');

    Comments

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.