You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JMeter内置提取器从JSON中随机提取数据集

使用JMeter内置提取器随机提取符合条件的JSON数据

前提说明

首先注意你的目标JSON存在语法错误:第三个和第四个对象之间缺少逗号,修正后才能被JMeter正确解析。另外,JSON中存在大小写不一致的rId/rid字段,后续步骤会兼容这两种写法。

步骤1:提取所有符合条件的条目

添加JSON Extractor到返回该JSON的Sampler下,配置如下:

  • 引用名称(Reference Name): matchingEntries
  • JSON路径表达式(JSON Path Expression): $..Documents[?((@.rId == 7 || @.rid == 7) && @.Name == 'Test_Kumar')]
    (该表达式会筛选出所有rId或rid为7且Name为Test_Kumar的条目)
  • 匹配编号(Match No.): -1(表示提取所有匹配的条目)
  • 计算串联变量(Compute concatenation var): 勾选(自动生成matchingEntries_matchNr变量,存储匹配到的条目总数)

步骤2:生成随机索引

添加JSR223 PreProcessor,使用Groovy脚本生成随机索引:

// 获取匹配条目总数
int totalEntries = vars.get("matchingEntries_matchNr") as int
if (totalEntries > 0) {
    // 生成1到totalEntries之间的随机整数(JMeter的匹配索引从1开始)
    int randomIdx = new Random().nextInt(totalEntries) + 1
    vars.put("randomIndex", String.valueOf(randomIdx))
} else {
    // 无匹配条目时的处理
    vars.put("randomIndex", "0")
}

步骤3:提取随机条目的字段

添加两个JSON Extractor分别提取选中条目的rId/rid和Name:

提取rId/rid

  • 引用名称: randomRid
  • JSON路径表达式: $..Documents[?((@.rId ==7 || @.rid ==7) && @.Name == 'Test_Kumar')][${randomIndex}].*id
  • 匹配编号: 1

提取Name

  • 引用名称: randomName
  • JSON路径表达式: $..Documents[?((@.rId ==7 || @.rid ==7) && @.Name == 'Test_Kumar')][${randomIndex}].Name
  • 匹配编号: 1

通用随机提取(无筛选条件)

如果不需要筛选,只想从Documents数组中随机提取任意一条数据:

  • 第一步的JSON路径改为$..Documents[*],引用名称设为allEntries
  • 脚本中使用allEntries_matchNr作为总数
  • 后续提取字段的JSON路径改为$..Documents[${randomIndex}].rId(或rid)和$..Documents[${randomIndex}].Name

内容的提问来源于stack exchange,提问作者Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:50:20