Home > Mobile >  Recursive function to handle tree json stops in the way
Recursive function to handle tree json stops in the way

Time:02-23

I have json tree, nested a few times, but final branch has answer.

[{
    "selects": [{
            "selects": [{
                "label":"A",
                "answer": "1"
            }]
        },
        {
            "selects": [{
                "label":"B",
                "answer": "2"
            }, {
                "selects": [{
                    "answer": "3"
                }, {
                    "answer": "4"
                }]

            }]
        }
    ]
}]

Now I want to change the all value of 'answers'

my current code is like this.

def double_answer(i):
    return int(i)*2

def parse(obj):
    #print(obj)
    if type(obj) is list:
        for i in obj:
            #print(i)
            return parse(i)
    else :
        #print(yourObj.keys())
        if 'selects' in obj.keys():
            return parse(obj['selects'])
        if 'answer' in obj.keys():
            obj['answer'] = double_answer(obj['answer'])

def run():
    dict = [{
        "selects": [{
            "selects": [{
                "label":"A",
                "answer": "2"
            }]
        },{
            "selects": [{
                "label":"B",
                "answer": "4"
            }, {
                "selects": [{
                    "answer": "6"
                }, {
                    "answer": "8"
                }]
            }]
        }]
    }]
    parse(dict)
    print(dict)

it shows.

[{'selects': [{'selects': [{'label': 'A', 'answer': 4}]}, {'selects': [{'label': 'B', 'answer': '4'}, {'selects': [{'answer': '6'}, {'answer': '8'}]}]}]}]

Now,first answer in json is changed to 4 (so ,it works for first item!!)

However recursive looks stop here.

I want to change other answers as well.

CodePudding user response:

The problem is with the return statement when you're parsing a list:

if type(obj) is list:
    for i in obj:
        #print(i)
        return parse(i)

This only recurses on the first value in the list, all the others won't be touched. If you want to handle the whole data structure, get rid of the return:

 if type(obj) is list:
    for i in obj:
        #print(i)
        parse(i)                        # don't return here!
  • Related