解决了它,也许它会被其他有类似问题的人使用。这里是 js 小提琴,http://jsfiddle.net/tF3uH/20/,并进一步参考代码
var data = {
"KeyA": ["KeyA0", "KeyA1"],
"KeyB": [{"KeyB0": ["KeyB00", "KeyB01"]}]
};
/* EXPECTED OUTPUT
[
{name: KeyA: children:[{name:KeyA0, children:[]},
{name:keyA1, children:[]}
]
},
{name: KeyB: children:[{name:KeyB0, children: [{name:KeyB00, children: []},
{name:KeyB01, children: []}
]
}
]
}
]
*/
function _doConversion(jsonData, treeList) {
if (typeof jsonData == typeof Object()) {
$.each(jsonData, function(key, val) {
var isArray = Array.isArray(val);
var name = key;
var children = [];
if (isArray) {
$.each(val, function(i, item) {
_doConversion(item, children);
});
}else{ //not array but object
_doConversion(val,children);
}
treeList.push({
name : name ,
children: children
});
});
} else { //a leaf (could be string,number,boolean...)
var node = {
name: jsonData,
children: []
};
treeList.push(node);
}
}
var list = [];
_doConversion(data, list);
$("body").text(JSON.stringify(list, null, "\n"));