1

image

在用postman进行接口测试的过程中,如果接口之间有依赖,那必然涉及到需要把接口的response结果的值提取出来给下一个接口使用。
今天我们就来讲一讲如何提取一个json类型的response里的数据。

假设我们的response如下。

{
    "dateSlots": [
        {
            "date": "2020-07-23",
            "available": true
        },
        {
            "date": "2020-07-24",
            "available": true
        }
    ],
    "timeSlots": [
        {
            "dealerId": "9",
            "advisorId": null,
            "date": "2020-07-23",
            "startTime": "9:00",
            "endTime": "9:30",
            "available": false
        },
        {
            "dealerId": "9",
            "advisorId": "ADV_490_13",
            "date": "2020-07-23",
            "startTime": "13:00",
            "endTime": "13:30",
            "available": true
        },
        {
            "dealerId": "9",
            "advisorId": "ADV_490_13",
            "date": "2020-07-23",
            "startTime": "13:30",
            "endTime": "14:00",
            "available": true
        }
    ]
}

1.提取所有response的值

pm.test("get timeslots", function(){

    var data = pm.response.json();

    console.log(data)

})

2.提取timeSlots里的值

pm.test("get timeslots", function(){

    var data = pm.response.json();

    console.log(data.timeSlots)

})

3.提取第一个dealerId的值

pm.test("get timeslots", function(){

    var data = pm.response.json();

    console.log(data.timeSlots[0].dealerId)

})

4.遍历所有的dealerId的值

pm.test("get timeslots", function(){

    var data = pm.response.json();
        
    _.each(data.timeSlots, (result) => {
        console.log(result.dealerId)
    })
})

5.找出所有available为true,dealerId不为null的advisorId的值

pm.test("get timeslots", function(){
    var data = pm.response.json();

    _.each(data.timeSlots, (result) => {
        if(result.available == true && result.advisorId != null){
            console.log(result.advisorId)
        }
    })
})

6.把所有的符合条件5的advisorId存到全局变量

把所有的advisorID存到一个数组中,名为advisorIds的全局变量中。
使用JSON.stringify(), 把数组值作为一个string存起来。

    var data = pm.response.json();
    let advisorIds = [];

    _.each(data.timeSlots, (result) => {
        if(result.available == true && result.advisorId != null){
            advisorIds.push(result.advisorId)
        }
    })

    pm.globals.set("advisorIds", JSON.stringify(advisorIds))

lucy
18 声望7 粉丝