如何将JSON数据从API响应传递到环境变量

时间:2019-08-12 09:52:53

标签: javascript api environment-variables postman

我正在使用POST方法创建一条记录,然后,当我收到JSON响应时,我想从该响应中获取“ id”,并将其传递到我已设置为“ formId”的Postman的环境变量中。 >

我尝试使用setEnvironmentVariable来设置json数据中记录为1的“ formId”,特别是“ id”数据。

pm.test("Pass new form id to environment variable", function(){
    var jsonData = pm.response.json();
    var formId =
    pm.setEnvironmentVariable("formId", jsonData[0].id);
})

这是我不断收到的错误:

将新的表单ID传递给环境变量| TypeError:无法读取未定义的属性“ id”

这是json响应:

{
    "created": "2019-08-12 05:45:35",
    "db": "1",
    "deleted": "0",
    "folder": "0",
    "id": "3548644",
    "language": "en",
    "name": "Test Form #3 - COPY 22",
    "num_columns": "1",
    "submissions": "0",
    "submissions_unread": "0",
    "updated": "2019-08-12 05:45:35",
    "viewkey": "coQv2xD54g",
    "views": "0",
    "submissions_today": 0,
    "data_url": "",
    "summary_url": "",
    "rss_url": "",
    "encrypted": false,
    "thumbnail_url": null,
    "submit_button_title": "Submit Form",
    "inactive": false,
    "timezone": "US/Eastern",
    "should_display_one_question_at_a_time": false,
    "can_access_1q_feature": true,
    "permissions": 150,
}

1 个答案:

答案 0 :(得分:2)

您共享的JSON响应中没有数组。 当您编写from(this.test).pipe(filter(a => a['department'] == 'dept1'), groupBy(a => a.id), mergeMap(a => a.pipe(toArray()))).subscribe(console.log); 时,这意味着您试图访问数组第0个索引处的值,但是jsonData是具有“ id”属性的对象,可以直接访问该属性。

您只需要在 Test 脚本(而不是Pre-request脚本)中编写此代码:

jsonData[0]

Test script