JavaScript JSON树(1个函数15行)来自单维或多维json对象的嵌套UI
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript JSON树(1个函数15行)来自单维或多维json对象的嵌套UI相关的知识,希望对你有一定的参考价值。
<!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>
以上是关于JavaScript JSON树(1个函数15行)来自单维或多维json对象的嵌套UI的主要内容,如果未能解决你的问题,请参考以下文章