每天進(jìn)步一點(diǎn)點(diǎn)~~文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-814525.html
背景:最近在寫接口自動(dòng)化的案例,其中一個(gè)功能是在es里面造數(shù),但是在造數(shù)前需要將原值清空,這樣會(huì)更方便直接一些;查詢接口會(huì)返回一個(gè)特定值:‘_id’,刪除接口需要這個(gè)值進(jìn)行指定刪除,返回結(jié)果是一段 json 串,要從里面取出需要的值
代碼舉例
- 注:接口請(qǐng)求在 postman 中,返回結(jié)果是一段 json ;但是在Pycharm中,接口請(qǐng)求的結(jié)果就會(huì)把JSON數(shù)據(jù)解析成Python對(duì)象,所以我是直接拿對(duì)象里面的值去遍歷的
- 正常流程是先導(dǎo)入 json 的包,然后用json.loads 方法進(jìn)行解析,這個(gè)講的比較好,我是直接在編輯器里面執(zhí)行,會(huì)比這個(gè)少一步解析的操作
https://geek-docs.com/python/python-ask-answer/605_python_looping_through_a_json_array_in_python.html文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-814525.html
- 以下是返回的結(jié)果值
{'took': 0, 'timed_out': False, '_shards': {'total': 5, 'successful': 5, 'failed': 0}, 'hits': {'total': 3, 'max_score': 3.3322046, 'hits': [{'_index': 'high_disp_retrieve_two_month_new', '_type': 'high_disp_retrieve_two_month_n
ew', '_id': 'AY0anzQGS_kZwf29X-kh', '_score': 3.3322046, '_source': {'inc_month': '202401', 'mobile_secret': 'mobile_no', 'user_group': 'P4', 'dec_type': 'real', 'task1_id': 'T1', 'task1_num': 2, 'task1_AB
_coupon': 'A', 'task2_id': 'T2', 'task2_num': 4, 'task2_AB_coupon': 'A', 'task3_id': 'T3', 'task3_num': 8, 'task3_AB_coupon': 'A', 'send_num': '35', 'model_type': '付款'}}, {'_index': 'high_disp_retrieve_two_month_new', '_type':
'high_disp_retrieve_two_month_new', '_id': 'AY0WNGvFS_kZwf29X-kN', '_score': 2.7725887, '_source': {'inc_month': '202310', 'mobile_secret': 'mobile_no', 'user_group': 'P2', 'dec_type': 'real', 'task1_id':
'T1', 'task1_num': 3, 'task1_AB_coupon': 'A', 'task2_id': 'T2', 'task2_num': 8, 'task2_AB_coupon': 'A', 'task3_id': 'T3', 'task3_num': 20, 'task3_AB_coupon': 'A', 'send_num': '35', 'model_type': '寄件'}}, {'_index': 'high_disp_
retrieve_two_month_new', '_type': 'high_disp_retrieve_two_month_new', '_id': 'AY0XC3-xS_kZwf29X-kd', '_score': 2.7725887, '_source': {'inc_month': '202312', 'mobile_secret': 'mobile_no', 'user_group': 'S1'
, 'dec_type': 'real', 'task1_id': 'T1', 'task1_num': 0, 'task1_AB_coupon': 'A', 'task2_id': 'T2', 'task2_num': 0, 'task2_AB_coupon': 'A', 'task3_id': 'T3', 'task3_num': 0, 'task3_AB_coupon': 'A', 'send_num': '35', 'model_type':
'寄件'}}]}}
# 獲取返回值,根據(jù) key 值將需要的內(nèi)容打印出來(lái)
r=requests.post(url=url,json=json_data)
result=r.json()
print(result)
print(result['hits']['hits'])
# for 循環(huán)遍歷結(jié)果中的 id 值,返回 id 值給刪除接口做入?yún)⑹褂?/span>
for _id in result['hits']['hits']:
id = _id['_id']
print(id)
return id
- 拿到返回的 _id 的值,傳給下個(gè)接口 delete 去做刪除操作
def test_deleteabnoaldata(self):
url='http://high_disp_retrieve_two_month_new/high_disp_retrieve_two_month_new'
delete_data=requests.delete(url=url + '/' + self.test_searchdata())
delete_result=delete_data.json()
assert delete_result['result'] == 'deleted'
print(delete_result)
到了這里,關(guān)于【Python】Python 中使用for循環(huán)取返回值 json 中的指定值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!