/ Published in: JavaScript
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)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<!DOCTYPE HTML> <head> <title>JSON Tree View</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js" type="text/javascript"></script> </head> <script> function json_tree(object){ var json="<ul>"; for(prop in object){ var value = object[prop]; switch (typeof(value)){ case "object": var token = Math.random().toString(36).substr(2,16); json += "<li><a class='label' href='#"+token+"' data-toggle='collapse'>"+prop+"="+value+"</a><div id='"+token+"' class='collapse'>"+json_tree(value)+"</div></li>"; break; default: json += "<li>"+prop+"="+value+"</li>"; } } return json+"</ul>"; } </script> <body style="margin: 40px;"> <h3>Paste Your JSON Into The Textarea Below and Click 'Build Tree'</h3> <p>If you do not see an unordered list appear after you click the button there is likely an error in your json. I used sample data I found at jQuery4u but only some of thier files validated when I ran them through json lint. The youtube example works, and the flickr example works after you delete the extra curly braces at the beginning and end of the data. If you are experiencing problems <ins>validate your json</ins> <a href="http://jsonlint.com/">Here</a>. Only valid json will produce a tree.</p> <textarea id="json" style="width: 100%;min-height:300px;"> </textarea> <button onclick="$('#output').html(json_tree(JSON.parse($('#json').val())));">Build Tree</button> <div id="output"> </div> </body> </html>