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,
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:
Here a small basic template example:
This will result in the following jQuery HTML element that can be appended to anywhere:
For your complex data, you can also iterate JSON sub objects using the “{{each}}” template notation. Here the code for your data and template:
Browsers Result:
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