0

I have a recursive traversal function to go through a JSON object and return the information that I want. The problem is that it's not returning anything. I know that the recursion is working properly because I modified to function to print out the input at each step and it was printing out the expected results - including the final step.

def wikipedia_JSON_traversal(wiki):
    if type(wiki)==dict:
        if 'definitions' in wiki.keys():
             wikipedia_JSON_traversal(wiki['definitions'])
        elif 'text' in wiki.keys():                       
             wikipedia_JSON_traversal(wiki['text'])
        else:
             pass
     elif type(wiki)==list:
        wikipedia_JSON_traversal(wiki[0])
    else:
        return wiki
1
  • There's no return statement anywhere in the if block. Commented Jul 27, 2018 at 17:52

1 Answer 1

1

You need a return after each function call, the returns don't bubble up automatically.

def wikipedia_JSON_traversal(wiki):
    if type(wiki)==dict:
        if 'definitions' in wiki.keys():
             return wikipedia_JSON_traversal(wiki['definitions'])
        elif 'text' in wiki.keys():                       
             return wikipedia_JSON_traversal(wiki['text'])
        else:
             pass
    elif type(wiki)==list:
        return wikipedia_JSON_traversal(wiki[0])
    else:
        return wiki
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! that did the trick! I spent several hours trying to debug this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.