【问题标题】:How to dynamically create and iterate Json Object inside a Json Array using Postman - Javascript如何使用 Postman - Javascript 在 Json 数组中动态创建和迭代 Json 对象
【发布时间】:2021-10-17 23:30:56
【问题描述】:

我有一个如下所述的有效负载:

{
  "id": "0001",
  "type": "donut",
  "name": "Cake",
  "ppu": 0.55,
  "batters": {
    "batter": [
      {
        "id": "1001",
        "type": "Regular"
      },
      {
        "id": "1002",
        "type": "Chocolate"
      },
      {
        "id": "1003",
        "type": "Blueberry"
      },
      {
        "id": "1004",
        "type": "Devil’sFood"
      }
    ]
  },
  "topping": [
    {
      "id": "5001",
      "type": "None"
    },
    {
      "id": "5002",
      "type": "Glazed"
    },
    {
      "id": "5005",
      "type": "Sugar"
    },
    {
      "id": "5007",
      "type": "PowderedSugar"
    },
    {
      "id": "5006",
      "type": "ChocolatewithSprinkles"
    },
    {
      "id": "5003",
      "type": "Chocolate"
    },
    {
      "id": "5004",
      "type": "Maple"
    }
  ]
}

**我想动态地增加 json 对象(它也可以是重复的),它位于基于数组大小的数组顶部。例如,如果将数组大小提到为 topping[10],则假设创建 10 个对象的有效负载并将这 10 个类似类型的对象推送到数组顶部 ** 是否可以动态创建 json 对象并在邮递员中发布请求??

温馨提示:数组的大小应该是参数化的。请告诉我。 请找到以绿色突出显示的图像。我想动态增加有效负载(使用邮递员基于索引的顶部数组大小

【问题讨论】:

    标签: javascript arrays json postman http-post


    【解决方案1】:

    你可以这样做:

    标签预请求

    let req = {
        "id": "0001",
        "type": "donut",
        "topping": []
    };
    
    let numberOfTopping = 5;
    
    for (let i = 0; i < numberOfTopping; i++) {
        let toppingItem = {
            "id": `${_.random(5001, 5010)}`,
            "type": `${_.sample(["Glazed", "Sugar", "None"])}`
        };
        req.topping[i] = toppingItem;
    }
    
    pm.variables.set("req", JSON.stringify(req));
    

    标签正文

    结果

    {
      "id": "0001",
      "type": "donut",
      "topping": [
        {
          "id": "5006",
          "type": "Glazed"
        },
        {
          "id": "5001",
          "type": "Sugar"
        },
        {
          "id": "5006",
          "type": "Glazed"
        },
        {
          "id": "5006",
          "type": "None"
        },
        {
          "id": "5008",
          "type": "Sugar"
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2018-10-19
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多