我有一个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