JSON Tree(1 function 15 lines)Nested Ul from single or multidimensional json object

/ Published in: JavaScript
Save to your folder(s)

Any valid json object will be recursively traversed building a nested unordered list of its properties and their values. This example parses the json entered in the text area into an object that is passed to the json_tree() function. I use the twitter bootstrap to make collapsible trees. That is the purpose of thee css and the random string i generate. I left it in as an example of how you might style the returned list. This is very much a work in progress so if you have any suggestions please post a comment. I have posted the entire html for a working example page just create the file and open it in your browser.(make sure your json validates - http://jsonlint.com - only valid json will produce a tree)

Copy this code and paste it in your HTML
  2. <head>
  3. <title>JSON Tree View</title>
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  5. <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" type="text/javascript"></script>
  7. </head>
  8. <script>
  9. function json_tree(object){
  10. var json="<ul>";
  11. for(prop in object){
  12. var value = object[prop];
  13. switch (typeof(value)){
  14. case "object":
  15. var token = Math.random().toString(36).substr(2,16);
  16. json += "<li><a class='label' href='#"+token+"' data-toggle='collapse'>"+prop+"="+value+"</a><div id='"+token+"' class='collapse'>"+json_tree(value)+"</div></li>";
  17. break;
  18. default:
  19. json += "<li>"+prop+"="+value+"</li>";
  20. }
  21. }
  22. return json+"</ul>";
  23. }
  24. </script>
  25. <body style="margin: 40px;">
  26. <h3>Paste Your JSON Into The Textarea Below and Click 'Build Tree'</h3>
  27. <p>If you do not see an unordered list appear after you click the button there is likely an error in your json.
  28. I used sample data I found at jQuery4u but only some of thier files validated when I ran them through json lint.
  29. The youtube example works, and the flickr example works after you delete the extra curly braces at the beginning
  30. and end of the data. If you are experiencing problems <ins>validate your json</ins> <a href="http://jsonlint.com/">Here</a>.
  31. Only valid json will produce a tree.</p>
  32. <textarea id="json" style="width: 100%;min-height:300px;">
  34. </textarea>
  35. <button onclick="$('#output').html(json_tree(JSON.parse($('#json').val())));">Build Tree</button>
  36. <div id="output">
  38. </div>
  39. </body>
  40. </html>

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.