class GetResponsePara():
def dict_get(self, dic, locators, default=None):
if not isinstance(dic, dict) or not isinstance(locators, list):
return default
value = None
for locator in locators:
if not type(value) in [dict, list] and isinstance(locator, str) and not self.can_convert_to_int(locator):
try:
value = dic[locator]
except KeyError:
return default
continue
if isinstance(value, dict):
try:
value = self.dict_get(value, [locator])
except KeyError:
return default
continue
if isinstance(value, list) and self.can_convert_to_int(locator):
try:
value = value[int(locator)]
except IndexError:
return default
continue
return value
def can_convert_to_int(self, input):
try:
int(input)
return True
except BaseException:
return False
def get_para2(self):
response = {"statusCode": 0, "message": "success", "data": {"token": {"session": [8888888]}, "onlyUser": 2}}
key = 'session'
path = 'data.token.session'
output = path.split('.')
for m in output:
if key in response:
print('==========', response[key])
return response[key]
response = response[m]
if __name__ == '__main__':
p = GetResponsePara()
dict_test = {"result": {"code": "110002", "msg": [{'status': 'ok'}, {'status': 'failed'}]}}
result = p.dict_get(dict_test, ['result', 'msg', '1', 'status'])
print(result)
dict_test = {"statusCode": 0, "message": "success", "data": {"token": "2C8A41292D428", "onlyUser": 2}}
result = p.dict_get(dict_test, ['data', 'token'])
print(result)
p.get_para2()
|