2

I am trying to traverse each 'node?' of a JSON objet in python. I am trying to implement a recursive function like

def function(data):
         for element in data:
                --- do something----
                if (some condition):
                        function(element)

what I want to know is how can I find if the element in question is another object or just a string. That is, what should I write instead of 'some condition' in my above code. Like when I travese an XML , I check if it has any children using getchildren() and if it does, I recursively call the function again.....

0

3 Answers 3

1

A good pythonic way to do it could be something like this :

def function(data):
   try:
      for element in data:
         --- do something----
         function(element)
   except TypeError:
      pass

Do the stuff and let python raise an exception if you try to iterate on something that is not iterable ;)

Sign up to request clarification or add additional context in comments.

Comments

1

Using type is generally frowned upon in Python in favor of the more-functional isinstance. You can also test multiple types at the same time using isinstance:

if isinstance(myVar, (list, tuple)):
  # Something here.

1 Comment

why? why is frowned upon type?
0

You could use the type(var) function to check whether the element is a dictionary or list.

def recurse(data):
    for element in data:
        if type(element) is list or type(element) is dict:
            recurse(element)
        else:
            # do something with element
            pass

Comments

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.