Home > Mobile >  recursive search json elements
recursive search json elements

Time:08-11

I'm having trouble with finding json elements in a nested json. It seems that my code only finds the element on the root level. My code is not able to find the elements recursively it seems.

import json
import pandas as pd

jsonString = '{"airplane": {"wings": {}, "wheels": {}, "cockpit": {}}}'

jsonObj = json.loads(jsonString)

data = ['airplane','wings','wheels','cockpit']

dfProp = pd.DataFrame(data, columns=['object'])

# find elements in JSON
for index, row in dfProp.iterrows():
    if row['object'] in jsonObj:   
        print(row['object']   ' '   'FOUND')
    else:
        print(row['object']   ' '   'NOT FOUND')
 

I want to find all elements regardless of how many nesting levels there are in json files. Can someone point me into the right direction?

Regards

CodePudding user response:

If I understand you correctly, you want to check if all values from list data is found as a key in jsonObj:

import json

jsonString = '{"airplane": {"wings": {}, "wheels": {}, "cockpit": {}}}'
jsonObj = json.loads(jsonString)


data = ["airplane", "wings", "wheels", "cockpit"]


def find(o):
    if isinstance(o, dict):
        for k, v in o.items():
            yield k
            yield from find(v)
    elif isinstance(o, list):
        for v in o:
            yield from find(v)


s = set(data).difference(find(jsonObj))
if not s:
    print("All values from data found in jsonObj")
else:
    print("Not all values from data found in jsonObj", s)

Prints:

All values from data found in jsonObj
  • Related