我有一個JSON對象是這樣的:遞歸問題;解析JSON
[{
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "sdfgdg1",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "sdfg2",
"morestuff": "",
}
},
{
"thing": "a",
"data": {
"text": "gfhjfghj3",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 4",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 5",
"morestuff": {
"thing": "Top",
"data": {
"childs": {
"thing": "a",
"data": {
"text": "asdfsadf 2 6",
"morestuff": "",
},
"data": {
"text": "asdfsadf 2 6",
"morestuff": "",
}
},
}
},
}
}],
}
},
}
}],
}
},
}
}],
}
},
}
},
{
"thing": "a",
"data": {
"text": "asdfasd1 2",
"morestuff": {
"thing": "Top",
"data": {
"childs": [{
"thing": "a",
"data": {
"text": "asdfsadf 2 3",
"morestuff": "",
}
}],
}
},
}
},
{
"thing": "a",
"data": {
"text": "dfghfdgh 4",
"morestuff": "",
}
}],
}
}]
...和我想通過它來迭代,並獲得「文本」對象總數。
我不能似乎能夠得到的東西遞歸工作..我想我失去了這兩個JSON和遞歸..
的基層瞭解這個幾個變化的天之後:
count=0;
c2=0;
c3=0;
function ra(arr){
//console.log(arr.data.morestuff)
if(arr!==undefined && arr.data && arr.data.morestuff===""){
c3++;
}else if((arr && arr.data && typeof arr.data.morestuff==="object")){
if(arr.data.morestuff.data.childs.length>1){
for(var w=0;w<arr.data.morestuff.data.childs.length;w++){
count+=ra(arr.data.morestuff.data.childs[w])
}
}else{
count+=ra(arr.data.morestuff.data.childs[0])
}
}
return(c3)
}
countn=0;//top morestuff with no morestuff
tot=0;
function reps(obj){
tot=obj.data.childs.length;
console.log("tot="+tot)
for(var x=0;x<tot;x++){
tot+=ra(obj.data.childs[x])
c3=0
if(tot>1000){//trying to prevent a runaway loop somehwere
break;
}
}
console.log(tot)
}
reps(json[0]);
我得出結論,我只是不知道。我得到各種不同的結果;有些人通過將ra方法的回報加在一起而接近,但沒有任何一致(即錯誤),並且總是至少少數。
JSON是一致的,雖然有未知數的兒童和兒童的孩子,這就是爲什麼我期待遞歸。
這裏是一個小提琴:http://jsfiddle.net/CULVx/
理想情況下,我想統計每個文本對象,它的相對位置,而且它有子女的數目,但我想我可以用得到的東西進入混亂一個數組,如果我只能得到計數工作...
注:我試過jsonParse和其他庫無濟於事。特別是,當試圖在這個json上使用它時,jsonParse會拋出一個Object has no method "match"
錯誤。
窩窩......只是用GSON人! – FUD
在最嵌套的對象中有兩個'data'屬性 - 是否正確? – pimvdb
我沒有使用java – stormdrain