Rama
Rama

Reputation: 49

Postman test save variable from JSON response body

I have json response body like this

{
    "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": []
}

I want to save two product_id values which have the most two stock than other

here my code

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)

Upvotes: 0

Views: 362

Answers (1)

Filip Culig
Filip Culig

Reputation: 125

The most simple solution to your problem would be implementing bubble sort for finding the product with the most stock.


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

Upvotes: 0

Related Questions