0

I have a JSON body response that has an array object in it.

{

     "tokens": [
        {
            "baseValue": "need this value to be extracted"
        }
    ]
}

The following test script is not able to extract it and set it in the environment variable

var jsonData = JSON.parse(responseBody);

    pm.test('get value from Response', function(){
            if ( jsonData.tokens.hasOwnProperty("baseValue") ) {
                var xauth = jsData.tokens.baseValue;
                 postman.setEnvironmentVariable("xauth", xauth);
            }
        });

What is wrong? Can someone help me achieve this

mack
  • 345
  • 5
  • 18

1 Answers1

0
var jsonData = JSON.parse(responseBody);

pm.test('get value from Response', function(){
        if ( jsonData.tokens[0].hasOwnProperty("baseValue") ) {
            var xauth = jsonData.tokens[0].baseValue;
             postman.setEnvironmentVariable("xauth", xauth);
        }
    });

The tokens property is an array and has a single object, you would need to add [0] in the reference to say that you want to use the baseValue property within the first object.

You could write it like this with the newer Postman syntax:

let jsonData = pm.response.json();

pm.test('get value from Response', function(){
        if ( jsonData.tokens[0].hasOwnProperty("baseValue")) {
             let xauth = jsonData.tokens[0].baseValue;
             pm.environment.set("xauth", xauth);
        }
    });
Danny Dainton
  • 23,069
  • 6
  • 67
  • 80