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

Tushar
  • 1,117
  • 1
  • 10
  • 25

2 Answers2

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

Tushar
  • 1,117
  • 1
  • 10
  • 25
  • What is this function for? – U13-Forward Sep 27 '18 at 09:06
  • 1
    As OP said `i want to iterate using recursive function`. – Tushar Sep 27 '18 at 09:07
  • 1
    @U9-Forward it's a dummy example (using recursion and `isinstance()` checks) of what the OP asks for. – bruno desthuilliers Sep 27 '18 at 09:08
  • i Did it..its a list...now how to iterate over 5 objects which is present inside the list using recursive function ? – Anonymous_hacker Sep 27 '18 at 09:23
  • 1
    `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 : https://ideone.com/OvEFk8 – Tushar Sep 27 '18 at 09:27
  • i did it bro but i guess its not going inside object @Tushar – Anonymous_hacker Sep 27 '18 at 09:41
  • {{ID: 1234,Custid:23456,req:{name:abc,std:2}}{ID:2789,custid:56897}} this is the json...i read it using loads in data – Anonymous_hacker Sep 27 '18 at 10:02
  • The data you gave doesn't look like a valid JSON. In fact, not even a valid python dictionary/list. You have 2 dictionaries inside 1 dictionary, without keys. That should be an array. I just updated the above example with your data, after adding quotes and replacing the outermost `{}` by `[]`, to make it a valid python structure. https://ideone.com/OvEFk8 – Tushar Sep 27 '18 at 12:13
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

U13-Forward
  • 69,221
  • 14
  • 89
  • 114