将JSON解析为HTML嵌套列表
JSON:
{ "Item 1": [ 9, { "Item 1.1" : 19, "Item 1.2" : 29, "Item 1.3" : 39 } ], "Item 2": 49, "Item 3": [ 59, { "Item 3.1" : 69, "Item 3.2" : 79, "Item 3.3" : 89 } ] }
期望的HTML:
我的尝试( http://jsbin.com/duxoyitifa/edit?js,console,output ):
$(document).ready(function() { var json = '{"Item 1":[9,{"Item 1.1":19,"Item 1.2":29,"Item 1.3":39}],"Item 2":49,"Item 3":[59,{"Item 3.1":69,"Item 3.2":79,"Item 3.3":89}]}'; var obj = $.parseJSON( json ); //console.log(obj); var items = []; $.each( obj, function( k1, v1 ) { console.log("k1: " + k1); console.log(v1); items.push(''); $.each( v1, function( k2, v2 ) { console.log(v2); items.push(''+k1+''); $.each (v2, function( k3, v3 ) { console.log(v3); }); }); items.push(' '); //items.push(''); //items.push(''+key+''); //items.push(' '); $("body").append(items.join( "" )); }); });
我无法想象如何从嵌套对象中获取n
和子列表。
$(document).ready(function() { var json = '{"Item 1":[9,{"Item 1.1":19,"Item 1.2":29,"Item 1.3":39}],"Item 2":49,"Item 3":[59,{"Item 3.1":69,"Item 3.2":79,"Item 3.3":89}]}'; var obj = $.parseJSON(json); //console.log(obj); var items = []; function eachObj(obj) { $.each(obj, function(key, value) { console.log("iteration start"); console.log(key, value); console.log("iteration end"); items.push(''); if (value != null && Array.isArray(value)) { items.push('' + key + ''); items.push(''); eachObj(value[1]); items.push('
'); } else { items.push('' + key + ''); } items.push(' '); }); } eachObj(obj); $('ul.list').html(items.join("")); });
将需要递归函数。
(当我找出一个确切的解决方案时,有些伪代码)
function parseForm(json){ var string = ""; function parseElement(j){ if(j.constructor === Object){ //write element to "string" for(var i=0; i
这无限深入。 此解决方案的关键是将递归部分夹在开始/结束标记之间。 我不确切知道格式化的规则是什么; 我会让你弄清楚具体的细节。