【问题标题】:Error in evaluating the test script when retrieving a string from the response in postman从邮递员的响应中检索字符串时评估测试脚本时出错
【发布时间】:2021-03-03 12:03:36
【问题描述】:

从下面的响应结构中,我想检索 id 字段并将其保存在邮递员的环境变量中。

我尝试了所有可能的方法,但无法做到。

{
    "childMaxAge": 13,
    "selectedForBooking": [
        {
            "id": "0661be61-d0ae-411009-a96d-64229a",
            "firstName": "Test",
            "gender": {
                "code": "MALE",
                "name": "Male"
            }
   ]
}

我尝试了以下方法,它也不起作用。

tests["Status code is 201"] = responseCode.code === 201;
var data = JSON.parse(responseBody);
console.log(data);
var custid=JSON.parse(data.selectedForBooking[0].id);
tests ["selectedForBooking"]= postman.setEnvironmentVariable("CustId1", custid);

但它给出了错误:

评估测试脚本时出错:JSONError: Unexpected token '6' at 1:2 0661be61-d0ae-411009-a96d-64229a ^

【问题讨论】:

    标签: parameters postman


    【解决方案1】:

    无需第二次解析响应数据。 如果您不打算断言任何内容,也无需使用tests[]

    tests["Status code is 201"] = responseCode.code === 201;
    var data = JSON.parse(responseBody);
    console.log(data);
    var custid=data.selectedForBooking[0].id;
    postman.setEnvironmentVariable("CustId1", custid);
    

    var custid=JSON.parse(data.selectedForBooking[0].id); 试图从0661be61-d0ae-411009-a96d-64229a 中创建一个 json 对象,这不是一个 json 格式的字符串。

    【讨论】:

    • 嗨,我尝试了你的建议,但也给出了错误“评估测试脚本时出错:TypeError:无法读取未定义的属性 'id'”
    • 您的错误表明“selectedForBooking”下的数组为空,您是否检查过实际返回的响应?你的服务是公开的吗?我可以向它发出请求吗?
    【解决方案2】:

    看看POSTMAN : parsing a JSON response, how deep can I go into the response?

    我曾经遇到过类似的问题,我正在尝试解决

    body.entries[0].attributes.device.type
    

    我设法通过这样做来获得价值

    body.entries[0].attributes['device.type']
    

    确保使用单引号(我不知道为什么......)

    希望对你有帮助

    亚历山大

    【讨论】:

    • 嗨,我尝试了你的建议,但也给出了错误“评估测试脚本时出错:TypeError:无法读取未定义的属性 'id'”
    • 好吧,这和我的情况不太一样,你有没有在测试前尝试过 console.log(custid) ?出现此错误,似乎 selectedForBooking[0] 无法识别...您是否也可以在控制台中查看 selectedForBooking[0] ?
    • ??为什么你json.parse数据,已经是一个json解析的结果了?
    【解决方案3】:

    您的 JSON 数据本身是错误的,这就是它显示该错误的原因。

    一定是这样的:

    {
        "childMaxAge": 13,
        "selectedForBooking": [
            {
                "id": "0661be61-d0ae-411009-a96d-64229a",
                "firstName": "Test",
                "gender": {
                    "code": "MALE",
                    "name": "Male"
                }
            }
       ]
    }
    

    现在你可以试试这个

    var custid=data.selectedForBooking[0].id;

    它将返回所需的值

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 2020-03-21
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2022-10-26
      相关资源
      最近更新 更多