Postman 中的 For 循环无法按预期工作 [英] For Loop in Postman not Working as Expected

查看:63
本文介绍了Postman 中的 For 循环无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Postman Runner 并运行 JSON 数据文件,并从控制台中的数据文件中取回每条记录.

I am trying to use Postman Runner and run through a JSON data file and get every record back from the data file in the console.

目前我只得到第一行.

我的 JSON 数据文件如下所示:

My JSON data file looks like this:

[
  {
    "line1": "13579",
    "line2": "2468",
    "line3": "1234",
    "line4": "5678",
  },
  {
    "line1": "13468",
    "line2": "2425",
    "line3": "12578",
    "line4": "567343",
  }
]

我尝试过的代码是:

var res = JSON.parse(responseBody);

for (let i = 0; i < res.length; i++) {
  console.log("actual data: " + i + " = " + data[i].line1);

    // tests start
    pm.test("iteration: " + i + " = " + "expected line1 = " + data.line1 + " | Actual line1 = " + res[i].line1 , function () {
        pm.expect(res[i].line1).to.equal(data[i].line1);
    });
}

但是,这会在控制台中打印出错误:

However, this prints out an error in the console:

"TypeError: Cannot read property 'line1' of undefined"

如果我将其更改为 console.log("actual data: " + i + " = " + data.line1);,它会写出:

If I change this to console.log("actual data: " + i + " = " + data.line1);, it then writes out:

actual data: 0 = 13579
actual data: 1 = 13579
actual data: 2 = 13579

[![Postman runner][1]][1]

[![Postman runner][1]][1]

  1. 我是否正确使用了 for 循环?
  2. 我做错了什么?

编辑
我忘记添加发送 URL 时 res 返回的内容:

[
  {
    "line1": "13579",
    "line2": "2468",
    "line3": "1234",
    "line4": "5678"
  },
  {
    "line1": "13468",
    "line2": "2425",
    "line3": "12578",
    "line4": "567343"
  },
  {
    "line1": "1test8",
    "line2": "24te25",
    "line3": "125st78",
    "line4": "567test343"
  }
]

推荐答案

使用数据文件的方式是 data["columnname"] 它没有多行.它不提供整个数据对象,而只提供当前迭代的数据.您不能使用数据对象遍历 csv 中的所有内容

The way to use data file is data["columnname"] it doesn't have multiple rows. It doesn't give the entire data object but only the data for current iteration so . you cannot use data object to iterate through all the content in the csv

尝试打印:

console.log( JSON.stringify(data))

如果您想使用 csv ,请将其存储为环境变量,然后使用它:

if you want to use csv , then store it as an environemnt variable and then use it :

示例:

https://documenter.getpostman.com/view/8296678/TzeUp9Me

使用此公共收藏

这篇关于Postman 中的 For 循环无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆