Skip to content

Instantly share code, notes, and snippets.

Last active January 18, 2024 05:33
Show Gist options
  • Save douglasmiranda/5127251 to your computer and use it in GitHub Desktop.
Save douglasmiranda/5127251 to your computer and use it in GitHub Desktop.
# 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

{'destination_addresses': ['Chennai, Tamil Nadu 600009, India'], 'origin_addresses': ['Chennai, Tamil Nadu 600101, India'], 'rows': [{'elements': [{'distance': {'text': '7.7 mi', 'value': 12327}, 'duration': {'text': '38 mins', 'value': 2285}, 'status': 'OK'}]}], 'status': 'OK'}

Hi Friends, from this JSON i need to extract the value '7.7' which is under the key 'text' under 'distance'. Can any one help in this

Copy link

chiranjeevijp commented May 6, 2020 via email

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