Adnan
Adnan

Reputation: 613

Traversing a JSON in Python

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.....

Upvotes: 2

Views: 4908

Answers (3)

Cédric Julien
Cédric Julien

Reputation: 80801

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 ;)

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 48018

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.

Upvotes: 1

Ross
Ross

Reputation: 47057

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

Upvotes: 0

Related Questions