Matts Matts - 3 months ago 8
JSON Question

How to return parents in path, and locate key in JSON

I'm trying to figure out how to find a key called ['text'] and then get the parent keys from the nest. It's the third key that's different, all the other tags are the same.

html_data = data['data']['document_data']['dataItem-ihmty5rw']['text']


I'm using this function to get the keys:

def printKeysValues(d):
for k, v in d.items():
if isinstance(v, dict):
printKeysValues(v)
else:
print("{0} : {1}".format(k, v))


And this function to find the indent:

def pretty(d, indent=0):
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))

Answer

I'm still not entirely sure if this is what you wanted, but if you just want the text per item dictionary, I think this should work:

# a dictionary of item string to dictionary containing a "text" key
item_map = data['data']['document_data']  

for item_string, item_map in item_map.iteritems():
    print item_string  # the item string (e.g. 'dataItem-ihmty5rw')
    print item_map['text']  # this is the text associated with the item string
Comments