Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unordered list from JSON Data?

I'd like to generate a tree view of my JSON data. Therefore it would be nice to parse the JSON data into a multi-level (!) unordered HTML list. I found a few plugins but I can't get them to work with my JSON data.

Nice solution would be a call to a function and hand over the json data as parameter. The result could be a multi-level unordered list. I assume that the function has to loop through all the JSON data and write ul and li tags.

Is there a straight forward way to do that?

tia!

PS: Example trees (that work with my JSOn data): http://braincast.nl/samples/jsoneditor/ http://www.thomasfrank.se/downloadableJS/JSONeditor_example.html

like image 318
manuel Avatar asked Jul 14 '11 11:07

manuel


People also ask

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.

Is JSON ordered or unordered?

A JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations. Keys are unique Strings that cannot be null. Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject.

What is Isjson?

JavaScript Object Notation (JSON) is the data-exchange format that makes this possible. JSON has become popular as a data format for developers because of its human-readable text, which is lightweight, requires less coding, and processes faster. Get started with Autonomous JSON Database.


2 Answers

Just a quick simple example:

function tree(data) {    
    if (typeof(data) == 'object') {
        document.write('<ul>');
        for (var i in data) {
            document.write('<li>' + i);
            tree(data[i]);            
        }
        document.write('</ul>');
    } else {
        document.write(' => ' + data);
    }
}

jQuery version:

function tree(data) {    
    if (typeof(data) == 'object') {        
        var ul = $('<ul>');
        for (var i in data) {            
            ul.append($('<li>').text(i).append(tree(data[i])));         
        }        
        return ul;
    } else {       
        var textNode = document.createTextNode(' => ' + data);
        return textNode;
    }
}

$(document.body).append(tree(data));
like image 55
Karolis Avatar answered Oct 18 '22 21:10

Karolis


Here is a complete pure javascript solution. Recursive traverse the JSON object and construct you ul and li's as you go. It's better for not to add elements to the DOM one at a time, though.

HTML

 <ul id="JSONunorderedList"></ul> 

JAVASCRIPT

var jsonObj ={"labels":[ {"labelFont":"35pt Calibri","labelLocation":{"x":0.1483, "y":0.75},  "labelText":"fluffer"},{"labelFont":"35pt Calibri","labelLocation":{"x":0.666, "y":0.666},  "labelText":"nutter"}]}; //some json to display

var listEl =document.getElementById('JSONunorderedList');
makeList(jsonObj,listEl);

function makeList( jsonObject, listElement){
    for(var i in jsonObject){//iterate through the array or object
        //insert the next child into the list as a <li>
        var newLI = document.createElement('li');
        if  (jsonObject[i] instanceof Array){
            newLI.innerHTML=i+": ARRAY";
            newLI.className="arrayOrObject"; //add a class tag so we can style differently
        }
        else if (  jsonObject[i] instanceof Object){
            newLI.innerHTML=i+": OBJECT";
            newLI.className="arrayOrObject"; //add a class tag so we can style differently
        }
        else
            newLI.innerHTML=i+': '+jsonObject[i];
        listElement.appendChild(newLI);   
        //insert a <ul> for nested nodes 
        if  (jsonObject[i] instanceof Array || jsonObject[i] instanceof Object){
            var newUL = document.createElement('ul');
            //newUL.innerHTML=i;
            listElement.appendChild(newUL);
            makeList(jsonObject[i],newUL);
        }
    }
}

das fiddle http://jsfiddle.net/honkskillet/LvMnG/

like image 45
honkskillet Avatar answered Oct 18 '22 22:10

honkskillet