Jmeter 聚合来自 json 的某些响应值以在下一个请求中使用

Jmeter aggregate certain response values from json to use in next request

我收到来自请求的以下响应

[
{
    "id": 3767,
    "sellerName": "abc",
    "siteActivity": [
        {
            "siteId": -1,
            "siteName": "example.com",
            "categories": [
                {
                    "categoryId": 79654,
                    "parentId": null,
                    "name": "Photo & Picture Frames",
                    "siteName": null,
                    "channelType": null
                },
                {
                    "categoryId": 114397,
                    "parentId": null,
                    "name": "Chests of Drawers",
                    "siteName": null,
                    "channelType": null
                },
                {
                    "categoryId": 11707,
                    "parentId": null,
                    "name": "Jewellery Boxes",
                    "siteName": null,
                    "channelType": null
                },
                {
                    "categoryId": 45505,
                    "parentId": null,
                    "name": "Serving Trays",
                    "siteName": null,
                    "channelType": null
                }
            ]
        }
    ]
},
{
    "id": 118156,
    "sellerName": "xyz",
    "siteActivity": [
        {
            "categoryId": 45505,
            "parentId": null,
            "name": "Serving Trays",
            "siteName": null,
            "channelType": null
        }
    ]
}
]

现在,我需要提取 "id" 值和 "categoryId" 值并将它们作为列表发送到下一个请求正文中。

目前,我正在使用 JSON 路径提取器和表达式

    $.[*].id

让我掌握所有 ID 和

    $.[*].siteActivity.[categoryId]

用于类别 ID。 接下来,我想使用上述值并将它们作为请求正文中的参数发送。 目前,我只能使用

提取一个 id
   $.[0].id

然后将其分配给变量 "id" 并在请求正文中使用以下内容

 {"ids":[{"id":"${id}"}]}

但我希望能够发送

 {"ids":[{"id":"${id}"},{"id":"${id2}"}....]}

ID 的数量没有限制,所以我不能硬编码,需要一些动态的东西来进行聚合。什么样的处理器可以帮助我?如果可以,请添加一些示例。

我相信您应该能够使用 Beanshell PostProcessor 来构建请求。

根据您的示例数据,您的 $.[*].id JSON 路径表达式应该 return 以下值:

id=[3767,118156]
id_1=3767
id_2=118156

所以基本上你需要:

  1. 确定"id"个数
  2. 填充动态JSON要发送的对象
  3. 保存到JMeter变量中以备后用

为此添加一个 Beanshell PostProcessor after JSONPath Extractor 并将以下代码放入其 "Script" 区域

import net.sf.json.JSONArray;
import net.sf.json.JSONObject; // necessary imports

JSONObject data2Send = new JSONObject();
JSONArray array = new JSONArray(); // instantiate JSON-related classes

int idCount = vars.get("id").split(",").length; // get "id" variables count

for (int i = 1; i <= idCount; i++) { // for each "id" variable
    JSONObject id = new JSONObject(); // construct a new JSON Object
    id.put("id", vars.get("id_" + i));// with name "id" and value id_X 
    array.add(id);  // add object to array
} 

data2Send.put("ids",array); // add array to "ids" JSON Object
vars.put("myJSON", data2Send.toString()); // store value as "myJSON" variable

您可以在需要时将您的 {"ids":[{"id":"3767"},{"id":"118156"}]} 数据称为 ${myJSON}

该方法适用于任意数量的 "id" 变量。

参考文献: