Extract a value from a json body response

Hello,

i want in postman using JS to extract a value from a json body response.The json looks like:

{

    "versionNameList": [
        "v1.1.0",
        "v1.1.1",
        "v1.1.2"
    ]
}

I want to select the last version v1.1.2 so using JMESPath i build this expresion and it seems to work:
grafik

So i tried in postman in Test Tab

// store POS Version to variable pos_version
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("pos_version", jsonData.versionNameList[-1]);

After the execution the variable is created but it is empty.When i use the expresion versionNameList[1] or versionNameList[2] it works fine,the corresponding value is set to variable.So it seems the problem is with -1

Why in JMESPath it works and in postman not?

Hi @oalimerko

I believe JMESPath is its own language, so not really surprised it doesn’t play well within Postman.

You could try something like this though;

//parse response
const response = pm.response.json();
//if you wanted to sort the array
let arr1 = response.versionNameList.sort();
//show sorted array
console.log(arr1);
//get last value in the array
console.log(arr1[arr1.length - 1]);

The bit you need I think is this;

versionNameList[versionNameList.length - 1]

Which basically takes the length of an array (remembering that the index starts at 0) and removes 1).

Hope that helps.

1 Like

hi @w4dd325 ,

it seems that your code works,at least i can see in console the version which i need.But how to store it in a variable?

Hello @oalimerko, you can save the value using below code

//set a global variable
pm.globals.set("variable_key","variable_value");
//set a collection variable
pm.collectionVariables.set("variable_key","variable_value");
//set an environment variable
pm.environment.set("variable_key","variable_value");

so your code will look something like below

pm.environment.set("version","arr1[arr1.length - 1]")

You can check more about variables here.

Cheers :magic_wand:

2 Likes