1. 程式人生 > >python接口自動化之-- json參數替換

python接口自動化之-- json參數替換

con AI PC publish ID type man init AD

#! /usr/bin/python
# coding:utf-8
# class changeData(object):

class getValues(object):
def __init__(self):
pass

#通過key獲取嵌套字典value
def get_target_value(self,key, dic, tmp_list):
"""
:param key: 目標key值
:param dic: JSON數據
:param tmp_list: 用於存儲獲取的數據
:return: list
"""
if not isinstance(dic, dict) or not isinstance(tmp_list, list): # 對傳入數據進行格式校驗
return ‘argv[1] not an dict or argv[-1] not an list ‘

if key in dic.keys():
tmp_list.append(dic[key]) # 傳入數據存在則存入tmp_list
else:
for value in dic.values(): # 傳入數據不符合則對其value值進行遍歷
if isinstance(value, dict):
print(‘看這裏‘,value)
self.get_target_value(key, value, tmp_list) # 傳入數據的value值是字典,則直接調用自身
elif isinstance(value, (list, tuple)):
self.get_value(key, value, tmp_list) # 傳入數據的value值是列表或者元組,則調用_get_value
return tmp_list

#通過key獲取嵌套字典value子方法
def get_value(self,key, val, tmp_list):
for val_ in val:
if isinstance(val_, dict):
self.get_target_value(key, val_, tmp_list) # 傳入數據的value值是字典,則調用get_target_value
elif isinstance(val_, (list, tuple)):
self.get_value(key, val_, tmp_list) # 傳入數據的value值是列表或者元組,則調用自身


#替換請求參數
"""
key:需要替換字典的key
dic:目標字典
changeData:替換值
"""
def replace_target_Value(self,key,dic,changeData):
if not isinstance(dic, dict): # 對傳入數據進行格式校驗
return ‘argv[1] not an dict or argv[-1] not an list ‘
if key in dic.keys():
dic[key]=changeData # 修改字典
else:
for value in dic.values(): # 傳入數據不符合則對其value值進行遍歷
if isinstance(value, dict):
self.replace_target_Value(key, value, changeData) # 傳入數據的value值是字典,則直接調用自身,將value作為字典傳進來
value[key]=changeData #替換key的value
elif isinstance(value, (list, tuple)):
self.replace_target(key, value, changeData) # 傳入數據的value值是列表或者元組,則調用_get_value
return dic

#替換參數子方法
#數據類型判斷,遍歷後分別調用不用的方法
def replace_target(self,key, val, changeData):
for val_ in val:
if isinstance(val_, dict):
self.replace_target_Value(key, val_, changeData) # 傳入數據的value值是字典,則調用replace_target_Value
elif isinstance(val_, (list, tuple)):
self.replace_target(key, val_, changeData) # 傳入數據的value值是列表或者元組,則調用自身

if __name__ == ‘__main__‘:
tmp_list=[]
tmp_dic={
‘respCode‘: ‘0000‘,
‘message‘: ‘success‘,
‘data‘: {
‘totalCount‘: 1,
‘totalPage‘: 1,
‘items‘: [{
‘publishTime‘: 12345678910,
‘totalAmount‘: 0,
‘projectId‘: ‘789‘
}]
}
}
test_dic={
‘respCode‘: ‘0000‘,
‘message‘: ‘success‘,
‘data‘: {
‘totalCount‘: 1,
‘totalPage‘: 1,
‘items‘: [{
‘publishTime‘: 1521083405000,
‘totalAmount‘: 0,
‘fullSuccessTime‘: 1521083405000,
‘submitTime‘: 1521082143000,
‘deadlineUnit‘: 1,
‘createTime‘: 1521082143000,
‘managementFee‘: ‘0.00‘,
‘penaltyFee‘: ‘0.00‘,
‘contractAmount‘: ‘3000.00‘,
‘days‘: 0,
‘borrowType‘: 1,
‘projectId‘: ‘57185181850095616‘
}]
}
}
print(type(test_dic))
#a=getValues().get_target_value(key=‘projectId‘,dic=test_dic,tmp_list=tmp_list)
print(‘替換前:‘,tmp_dic)
b=getValues().replace_target_Value(key=‘projectId‘,dic=tmp_dic,changeData=‘57185181850095616‘)

print(‘替換後:‘,b)

python接口自動化之-- json參數替換