Skip to content

Instantly share code, notes, and snippets.

@tylerneylon
Created September 28, 2022 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerneylon/32ed873ec71f5065460cb0c44233678c to your computer and use it in GitHub Desktop.
Save tylerneylon/32ed873ec71f5065460cb0c44233678c to your computer and use it in GitHub Desktop.
A little function to help analyze / debug / understand a json object.
def call_on_leaves(json_obj, fn, path=None):
path = path or []
if type(json_obj) is dict:
for k, v in json_obj.items():
if not call_on_leaves(v, fn, path + [k]):
return False
elif type(json_obj) is list:
for i, v in enumerate(json_obj):
if not call_on_leaves(v, fn, path + [i]):
return False
else:
return fn(json_obj, path)
@tylerneylon
Copy link
Author

This function calls fn() on all the leaf values of json_obj. For each leaf value, fn() receives the value as the first argument, and the path to that leaf as its second argument. A path is a Python list of keys (for dictionaries) and integer indexes (for JSON lists).

If you'd like the walk to continue, return True from fn(); otherwise return False, and the walk will immediately stop.

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