這可能是重複的,但我還沒有找到我的問題的解決方案,即使我已經檢查了許多JSON遞歸traversion功能的其他示例。迭代通過嵌套的數字鍵json對象
我的JSON OBJ看起來有點像下面這樣:
function recurTrav (jsonObj) {
$.each(jsonObj.description[0], function (key, value) {
$(".testul").append("<li class=" + key + ">" + value + "</li>");
if (typeof(jsonObj[key] == "object")) {
recurTrav(jsonObj[key]);
}
});
}
recurTrav(obj);
給我什麼:
var obj =
{
"description": [
{
"list": [
{
"1": "here is text"
},
{
"2": "other text"
},
{
"3": "arbitrary text"
},
{
"4": [
{
"1": "indented"
},
{
"2": {
"1": "indented to second level"
}
},
{
"3": "first indentation level again"
},
{
"4": {
"1": "second level again"
}
},
{
"5": "and first level, to wrap things up"
}
]
}
]
}
]
};
的東西,如穿越這一點。 (請注意,這是隻是爲了測試我怎麼會遍歷。我卡住了,這是令人尷尬的。
我想我會只需要在正確的方向一推......
我其實是什麼希望做的是創造成一個無序列表結構。凡有可能成爲主要的UL內ULS這一點。
<ul>
<li>here is text</li>
<li>other text</li>
<li>arbitrary text</li>
<li>
<ul>
<li>indented</li>
<li>
<ul>
<li>indented to second level</li>
</ul>
</li>
<li>first indentation level again</li>
<li>
<ul>
<li>second level again</li>
</ul>
</li>
<li>and first level, to wrap things up</li>
</ul>
</li>
</ul>
什麼是你traversion規則?現在甚至沒有像'for'循環那樣的迭代,因爲你的'jsonObj [key]'不會產生包含'.description'列表的東西 – twil
我不確定這是否是唯一的問題,但是括號會混淆在你的'如果'檢查。它應該是'if(typeof(jsonObj [key])==「object」)' –
@PatrickQ是的,對不起,我輸入的代碼很快且很髒,可以確認這不是實際的問題。它產生了一堆不穿過的對象。 – NicT