Created
May 9, 2018 21:06
-
-
Save Sonictherocketman/00155ed9e0e0f9c0d631aa3f753b9f8c to your computer and use it in GitHub Desktop.
Get values from nested structures in Python.
This file contains hidden or 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 query(q, data, default=None, should_raise=False): | |
| """ This method allows for a simple recursive queries on JSON fields, | |
| including Python's native dictionary. | |
| Sample query: | |
| data = { | |
| 'user' { | |
| 'aliases': [ | |
| { | |
| 'name': 'Joe' | |
| }, { | |
| 'name': 'Joey' | |
| } | |
| ] | |
| } | |
| } | |
| data.query('user.aliases.0.name') | |
| >>> 'Joe' | |
| """ | |
| try: | |
| return _query(data, q) | |
| except (KeyError, ValueError, IndexError) as e: | |
| if not should_raise: | |
| return default | |
| else: | |
| raise e | |
| def _query(data, q): | |
| first, *rest = q.split('.', maxsplit=1) | |
| try: | |
| first = int(first) | |
| except ValueError: | |
| pass | |
| data = data[first] | |
| if rest: | |
| return _query(data, rest[0]) | |
| else: | |
| return data | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment