Skip to content

Instantly share code, notes, and snippets.

@tvboxme
Created April 26, 2018 03:15
Show Gist options
  • Save tvboxme/934dbebca40d34d30bb6f50cc63949fc to your computer and use it in GitHub Desktop.
Save tvboxme/934dbebca40d34d30bb6f50cc63949fc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# encoding: utf-8
# author: 04
def doc_xpath(doc, xpath):
"""
>>> a = {'a': [{'b': {'c': ['d', 'f']}}, {'b': {'c': ['g', 'h']}}]}
>>> doc_xpath(a, 'a.b')
Traceback (most recent call last):
...
ValueError: Xpath <a.b> failed at <b>.
>>> doc_xpath(a, 'a.[].b.c')
[['d', 'f'], ['g', 'h']]
>>> doc_xpath(a, 'a.[].b.c.[]')
['d', 'f', 'g', 'h']
"""
check_points = [doc]
for word in xpath.split('.'):
new_points = []
for point in check_points[:]:
try:
if word == '[]':
if not isinstance(point, list):
raise ValueError()
new_points.extend(point)
else:
if not point.get(word):
raise ValueError()
new_points.append(point.get(word))
except Exception:
raise ValueError('Xpath <%s> failed at <%s>.' % (xpath, word))
check_points = new_points
return check_points
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment