json 如何在Postman中从响应体创建变量?

fdbelqdn  于 2022-11-19  发布在  Postman
关注(0)|答案(1)|浏览(182)

我有如下的React体:`

{
    "timestamp": "2022-11-08T12:40:11.631Z",
    "data": {
        "version": "2.2",
        "endpoints": [
            {
                "identifier": "credentials",
                "role": "SENDER",
                "url": "https://example.com/credentials65"
            },
            {
                "identifier": "tokens",
                "role": "RECEIVER",
                "url": "https://example.com/tokens245"
            },
            {
                "identifier": "tokens",
                "role": "SENDER",
                "url": "https://example.com/tokens353"
            },
.......

对于每个标识符和角色(在Postman测试会话中),我希望自动定义变量。
我尝试了以下的第一个:

_.each(pm.response.json(), (responseBody) => {

        if (responseBody.identifier['data'][1]['identifier'] === "credentials") { 
           pm.globals.set("credentials_url", responseBody.url)
        }

        else if (responseBody.identifier === "tariffs") {
           pm.globals.set("tariffs_url", responseBody.url)
        }

    })

问题是我不知道如何调用“标识符”,脚本没有进入if循环。有人能帮助吗?

uinbv5nw

uinbv5nw1#

const endpoints = pm.response.json().data.endpoints;
for (const endpoint of endpoints) {
    const array = pm.globals.get(`${endpoint.identifier}_url`) ?? [];
    array.push(endpoint.url);
    pm.globals.set(`${endpoint.identifier}_url`, array);
}

您可以使用pm.globals.get("tariffs_url")pm.globals.get("credentials_url")等访问数组中的URL(它适用于每个标识符)

相关问题