Skip to content

Instantly share code, notes, and snippets.

@Sonictherocketman
Created May 9, 2018 21:06
Show Gist options
  • Select an option

  • Save Sonictherocketman/00155ed9e0e0f9c0d631aa3f753b9f8c to your computer and use it in GitHub Desktop.

Select an option

Save Sonictherocketman/00155ed9e0e0f9c0d631aa3f753b9f8c to your computer and use it in GitHub Desktop.
Get values from nested structures in Python.
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