来自JSON响应正文的邮递员测试保存变量

时间:2020-08-25 06:44:36

标签: postman

我有这样的json响应正文

{
    "header": {
        "process_time": "27.842975",
        "server_time": "",
        "reason": "",
        "error_code": 0,
        "status_code": 200
    },
    "data": {
        "idx": "2",
        "component": {
            "id": 123,
            "name": "product",
            "properties": {
                "button_notification": false
            },
            "title": "",
            "data": [
                {
                  "status": 4,
                    "product_id": 1112323,
                    "stock": 21
                },
                {
                  "status": 4,
                    "product_id": 1114322,
                    "stock": 13
                },
                {
                    "status": 4,
                    "stock": 8,
                    "product_id": 1115342
                },
                {
                    "stock": 5,
                    "status": 4,
                    "product_id": 1115234
                },
                {
                    "stock": 5,
                    "status": 4,
                    "product_id": 1115442
                }
            ]
        }
    },
    "errors": []
}

我要保存两个product_id值,该值比其他值最多两个

这里是我的代码

var jsonData = JSON.parse(responseBody);
let productId-1 = jsonData.data.component.data[2].product_id
let productId-2 = jsonData.data.component.data[3].product_id
pm.environment.set("productId-1",productId-1)
pm.environment.set("productId-2",productId-2)

1 个答案:

答案 0 :(得分:0)

解决您问题的最简单方法是实施气泡排序,以找到库存最多的产品。


let arr = jsonData.data.component.data; 
for(let i = 0; i < arr.length - 1; i++){
    for(let j = 0; j < arr.length - 1 - i; j++){
        if (arr[j].stock < arr[j+1].stock) { 
            let temp = arr[j]; 
            arr[j] = arr[j+1]; 
            arr[j+1] = temp; 
        } 
    } 
} 
pm.environment.set("productId-1", arr[0]); //product with most stock
pm.environment.set("productId-2", arr[1]); //product with second most stock