1

I have one json file which i want to iterate using recursive function , but how to check whether my json structure is string , array , list or object ?

If its array and inside array there are 5 objects how to access objects using recursive function in python ?

{{ID: 1234,Custid:23456,req:{name:abc,std:2}}{ID:2789,custid:56897}} this is the json...i read it using loads in data

3
  • 2
    use isinstance. Commented Sep 27, 2018 at 8:53
  • Possible duplicate of What's the canonical way to check for type in Python? Commented Sep 27, 2018 at 9:04
  • can you show algorithm for that..considering i loaded my json file in variable 'data' ? @mehrdad-pedramfar Commented Sep 27, 2018 at 9:05

2 Answers 2

2

Use recursion, and use type() or isinstance() to decide what to do.

def handle(x):
    if isinstance(x, dict):
        # do dict stuff
        for key, val in x.items():
            handle(val)
    elif isinstance(x, list):
        # do list stuff
        for val in x:
            handle(val)
    elif isinstance(x, str):
        # do string stuff
        print(x)
    elif isinstance(x, (int, float)):
        # maybe integer, float, etc
        print(x)
    else:
        print("None???")

d = json.loads(json_string)

handle(d)

Above recursive implementation will handle your use case of array in array, dict in array, etc

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

8 Comments

What is this function for?
As OP said i want to iterate using recursive function.
@U9-Forward it's a dummy example (using recursion and isinstance() checks) of what the OP asks for.
i Did it..its a list...now how to iterate over 5 objects which is present inside the list using recursive function ?
for val in x: above will iterate over them one by one. It will again call the recursive handle, which will take care of the values in that array, whatever it is. Just try running the above code with different values of json_string. Here : ideone.com/OvEFk8
|
1

Use isinstance:

s='this is a string (str)'
if isinstance(s,str):
    do something

Also able to do multiple like:

isinstance(s,(str,int))

Or more inefficient way by checking type:

if type(s) is str:
    do something

This is able to use multiple like:

type(s) in (str,int)

But in these solutions i recommend to use isinstance

1 Comment

as a general rule, isinstance() is the recommanded way unless you really want to check the exact type.

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.