1818import hashlib
1919import json
2020import random
21+ import re
22+
23+ field_match = re .compile (r"(?:(\w+)\((\w+(?:,\w+)*)\))|(\w+)" )
2124
2225
2326def filter_fields_from_response (fields , response ):
@@ -33,23 +36,29 @@ def filter_fields_from_response(fields, response):
3336 if fields is None :
3437 return json .dumps (response )
3538 tmp = {}
36- for key in fields .split ("," ):
37- key .replace (" " , "" )
38- parentheses_idx = key .find ("(" )
39- if parentheses_idx != - 1 :
40- main_key = key [:parentheses_idx ]
41- child_key = key [parentheses_idx + 1 : - 1 ]
42- if main_key in response :
43- children = response [main_key ]
44- if isinstance (children , list ):
45- tmp_list = []
46- for value in children :
47- tmp_list .append (value [child_key ])
48- tmp [main_key ] = tmp_list
49- elif isinstance (children , dict ):
50- tmp [main_key ] = children [child_key ]
51- elif key in response :
52- tmp [key ] = response [key ]
39+ fields .replace (" " , "" )
40+ for keys in field_match .findall (fields ):
41+ if keys [2 ]:
42+ if keys [2 ] not in response :
43+ continue
44+ tmp [keys [2 ]] = response [keys [2 ]]
45+ else :
46+ if keys [0 ] not in response :
47+ continue
48+ childrens = response [keys [0 ]]
49+ if isinstance (childrens , list ):
50+ tmp_list = []
51+ for children in childrens :
52+ child = {}
53+ for child_key in keys [1 ].split ("," ):
54+ child [child_key ] = children [child_key ]
55+ tmp_list .append (child )
56+ tmp [keys [0 ]] = tmp_list
57+ elif isinstance (childrens , dict ):
58+ child = {}
59+ for child_key in keys [1 ].split ("," ):
60+ child [child_key ] = children [child_key ]
61+ tmp [keys [0 ]] = child
5362 return json .dumps (tmp )
5463
5564
0 commit comments