Last active
November 12, 2015 03:09
-
-
Save Zephor5/9b626cfb825db14728c4 to your computer and use it in GitHub Desktop.
a simple json search
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 search_json(data, s): | |
""" | |
search in json | |
example data is {"items": [{"url": "1"}, {"url": "2"}]} | |
s is items->[]->url then get ["1", "2"] | |
s is items->[0]->url then get ["1"] | |
:rtype: generator | |
""" | |
structs = s.split('->') | |
lists = [] | |
def gen_lists(_data, _structs): | |
while _structs: | |
_p = _structs.pop(0) | |
if _p.startswith('[') and _p.endswith(']'): | |
_p = _p[1:-1] | |
if _p: | |
_data = _data[int(_p)] | |
else: | |
lists.append((_data, 0, list(_structs))) | |
_data = _data[0] | |
else: | |
_data = _data[_p] | |
return _data | |
data = gen_lists(data, structs) | |
if not lists: | |
yield data | |
while lists: | |
for i in xrange(len(lists)): | |
if i == 0: | |
_list, _, structs = lists.pop(-1) | |
for data in _list: | |
for p in structs: | |
data = data[p] | |
yield data | |
else: | |
_list, j, structs = lists.pop(-1) | |
if j+1 < len(_list): | |
lists.append((_list, j+1, structs)) | |
gen_lists(_list[j+1], structs) | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment