Created
September 28, 2022 20:55
-
-
Save tylerneylon/32ed873ec71f5065460cb0c44233678c to your computer and use it in GitHub Desktop.
A little function to help analyze / debug / understand a json object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This function calls
fn()
on all the leaf values ofjson_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
fromfn()
; otherwise returnFalse
, and the walk will immediately stop.