Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# This is a really old post, in the comments (and stackoverflow too) you'll find better solutions.
def find(key, dictionary):
for k, v in dictionary.iteritems():
if k == key:
yield v
elif isinstance(v, dict):
for result in find(key, v):
yield result
elif isinstance(v, list):
for d in v:
for result in find(key, d):
yield result
example = {'app_url': '', 'models': [{'perms': {'add': True, 'change': True, 'delete': True}, 'add_url': '/admin/cms/news/add/', 'admin_url': '/admin/cms/news/', 'name': ''}], 'has_module_perms': True, 'name': u'CMS'}
list(find('admin_url', example))
Copy link

beeoss commented Apr 8, 2021

Hello all.. Could anyone help me Python parse and print < "name" , "raw" > (values only), from the JSON below?

{"count":57,"next":null,"previous":null,"results":[{"id":229,"state":"complete","substate":null,"exceptions":[],"name":"Sender Account Number","output_name":null,"field_definition_attributes":{"required":false,"data_type":"Account Number","multiline":false,"routing":false,"supervision_override":null},"transcription":{"raw":"1957-3549-2","normalized":"195735492","source":"machine_transcription","data_deleted":false,"user_transcribed":null},"field_image_url":"/api/v5/image/613cf762-b4bc-46f0-a511-3dc8bb37eae3?start_x=0.3110429607297866&start_y=0.1052441592299208&end_x=0.5696909842243418&end_y=0.16043316955780607","page_id":5}

So for the 'Item' included above, starting at "results": and nesting node to "transcription", the parsed values need to be:

Sender Account Number, 1957-3549-2
(repeating items) 'for'

Much thanks for any assistance!!

Copy link

sahil-developer commented Jul 27, 2021

Thanks for the help.
Python3 users should replace dictionary.iteritems() with dictionary.items(). iteritems was removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment