PythonPython 中使用for循环取返回值 json 中的指定值

每天进步一点点~~

背景:最近在写接口自动化的案例,其中一个功能是在es里面造数,但是在造数前需要将原值清空,这样会更方便直接一些;查询接口会返回一个特定值:‘_id’,删除接口需要这个值进行指定删除,返回结果是一段 json 串,要从里面取出需要的值

代码举例

  • 注:接口请求在 postman 中,返回结果是一段 json ;但是在Pycharm中,接口请求的结果就会把JSON数据解析成Python对象,所以我是直接拿对象里面的值去遍历的
  • 正常流程是先导入 json 的包,然后用json.loads 方法进行解析,这个讲的比较好,我是直接在编辑器里面执行,会比这个少一步解析的操作

Python 在Python中循环遍历JSON数组

  • 以下是返回的结果值
{'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': 
'寄件'}}]}}

        # 获取返回值,根据 key 值将需要的内容打印出来
        r=requests.post(url=url,json=json_data)
        result=r.json()
        print(result)
        print(result['hits']['hits'])

        # for 循环遍历结果中的 id 值,返回 id 值给删除接口做入参使用
        for _id in result['hits']['hits']:
            id = _id['_id']
            print(id)
            return id
  • 拿到返回的 _id 的值,传给下个接口 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)