Last active
December 15, 2015 07:29
-
-
Save thiago/5223846 to your computer and use it in GitHub Desktop.
Converte parâmetros de uma string e retorna um dicionário. O formato da string é bem parecido com a nova api do facebook: https://developers.facebook.com/tools/explorer
This file contains 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
#Example usage | |
# string = "user(1),about,accounts.limit(20).fields(hometown,albums.limit(10).fields(comments))" | |
# parsed = parse_params(string) | |
# parsed = { | |
# 'about': None, | |
# 'accounts': { | |
# 'fields': { | |
# 'hometown': None, | |
# 'albums': { | |
# 'fields': { | |
# 'comments': None | |
# }, | |
# 'limit': '10' | |
# } | |
# }, | |
# 'limit': '20' | |
# }, | |
# 'user': '1' | |
#} | |
def parse_params(str): | |
attrs = [] | |
aux = str | |
arr = {} | |
attr = '' | |
_sub_attr = '' | |
r = 0 | |
f = 0 | |
v = 0 | |
d = 0 | |
_c_value = None | |
_sub = 0 | |
_p_start = 0 | |
i = 0 | |
for c in aux: | |
if c == '(': | |
r += 1 | |
f = 1 | |
if _p_start == 0: | |
_p_start = i | |
elif c == ')': | |
r -= 1 | |
elif c == '.': | |
d = 1 | |
_sub = 1 | |
elif c == ',': | |
v = 1 | |
if v == 0 and _sub == 0: | |
attr += c | |
if _sub == 1: | |
if d == 0 and f == 0 and v == 0: | |
_sub_attr += c | |
if r == 0 and f == 1: | |
_c_value = str[_p_start + 1: (i - _p_start + 1) + _p_start - 1] | |
if _sub == 0: | |
attr = attr.replace('(' + _c_value + ')', '') | |
else: | |
_sub_attr = _sub_attr.replace(_c_value, '') | |
if len(_sub_attr) > 0: | |
arr[attr] = arr[attr] if attr in arr else {} | |
arr[attr][_sub_attr] = _c_value | |
if _sub_attr == "fields": | |
arr[attr][_sub_attr] = parse_params(_c_value) | |
else: | |
arr[attr] = _c_value | |
_c_value = '' | |
_sub_attr = '' | |
_p_start = 0 | |
f = 0 | |
if (v and r == 0) or i == len(aux) - 1: | |
if attr not in arr: | |
arr[attr] = None | |
attr = '' | |
_sub = 0 | |
v = 0 | |
d = 0 | |
i += 1 | |
return arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment