从JSON数据生成无序列表? [英] Generate unordered list from JSON Data?

查看:213
本文介绍了从JSON数据生成无序列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成我的JSON数据的树形视图。因此,将 JSON数据解析为多层(!)无序HTML列表会很好。我发现了一些插件,但我无法让他们使用我的JSON数据。



好的解决方案是调用函数并将json数据作为参数。结果可能是多级无序列表。我假设函数必须遍历所有JSON数据并写入 ul li 标记。

有没有一个简单的方法来做到这一点?



tia!



PS:与我的JSOn数据):
http://braincast.nl/samples/jsoneditor/
http ://www.thomasfrank.se/downloadableJS/JSONeditor_example.html

解决方案

只是一个简单的例子:

 函数树(数据){
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);


$ / code $ / pre
$ b $ j jQuery版本

 函数树(数据){
if(typeof(data)=='object'){
var ul = $('< ; UL>');
for(var i in data){
ul.append($('< li>).text(i).append(tree(data [i])));
}
返回ul;
} else {
var textNode = document.createTextNode('=>'+ data);
返回textNode;
}
}

$(document.body).append(tree(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 the 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

解决方案

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));

这篇关于从JSON数据生成无序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆