【问题标题】:How to grab variable from one API that is within a nested Array response body?如何从嵌套数组响应正文中的一个 API 中获取变量?
【发布时间】:2021-01-31 11:17:27
【问题描述】:

如何获取 contentID 和内容标题,将其添加到数组中并在 API 2 的 URL 中使用

如果我将下面的代码用于节标题和 sectionid,它可以工作,因为它不在嵌套数组中,但对于 contentid 和 contenttitle,它不像在嵌套数组中那样工作。

在 API 1 测试选项卡中我有:

for (i = 0; i < resultCount; i++) {
    var id = jsonData[i].contents[0].contentId;
    var modelString = jsonData[i].contents[0].contentTitle;
    console.log(id)
    console.log(modelString)

    if (modelString.includes(“APIAUTOMATIONcontent”) || modelString.includes(“Testcontent”) || modelString.includes("{{POST-NewSlide}}") || modelString.includes(“stringcontent”)) {
        hasDelete.push(id);
        // (id) - this creates an integer (int)
        //   "announcementId": id,   (creating object)
        //   "hasDelete": modelString.includes("Delete") || modelString.includes("Test")
        // });
    } else {
        doesntHaveDelete.push(id)
        //   "announcementId": id
        // });
    }
}

// Check that each object in response contained keyword and length matches from test

pm.test(Number of Content that has APIAUTOMATIONcontent or Test ready to be deleted = ${hasDelete.length} out of Total ${resultCount} , function() {
    console.log(hasDelete);
    console.log(doesntHaveDelete);
    pm.expect(hasDelete.length);
});

pm.collectionVariables.set(‘deletesections’, JSON.stringify(hasDelete));

【问题讨论】:

    标签: arrays json postman postman-pre-request-script postman-testcase


    【解决方案1】:

    就像您在响应正文中遍历每个 section 一样,您还需要遍历 contents 数组,您可以像下面这样:

    for (i = 0; i < resultCount; i++) {
    
        contentCount = jsonData[i].contents.length;
        for (j = 0; j < contentCount; j++) {
            let content = jsonData[i].contents[j];
            console.log(content.contentId);
            console.log(content.sectionId);
            console.log(content.contentTitle);
            console.log(content.pdfLink);
            console.log(content.videoLink);
            console.log(content.sortOrder);
        }
    }
    

    【讨论】:

    • 感谢 (i = 0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多