Skip to content

Instantly share code, notes, and snippets.

@andreastt
Last active October 15, 2020 11:37
Show Gist options
  • Save andreastt/d28ae7d740be19ebc8ea3541403c822c to your computer and use it in GitHub Desktop.
Save andreastt/d28ae7d740be19ebc8ea3541403c822c to your computer and use it in GitHub Desktop.
def get_path(json, path, default=None):
cur, _, rest = path.partition(".")
if cur in json:
if len(rest) > 0:
return get_path(json[cur], rest)
else:
return json[cur]
return default
if __name__ == "__main__":
assert get_path({"foo": {"bar": 42}}, "foo.bar") == 42
assert get_path({"foo": "bar"}, "foo") == "bar"
assert get_path({}, "foo") == None
assert get_path({}, "foo", "bar") == "bar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment