0

我有一个 JSON 正文响应,其中包含一个数组对象。

{

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

以下测试脚本无法将其提取并设置在环境变量中

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);
            }
        });

怎么了?有人可以帮我实现这一目标

4

1 回答 1

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);
        }
    });
于 2020-04-16T20:11:15.867 回答