0

JMeter JSON Extractor对数组不一致的foreach控制器使用-1值

我有这个 JSON 响应

[
  {
    "userId": 1,
    "id": 1,
    "title": " How to Shape of Character Design",
    "write": "Jun Bale",
    "date": "20/12/20",
    "time": "10:00AM",
    "body": " Because he takes  nsuscipit accepted result lightly with  nreprehenderit discomfort may be the entire  nnostrum of the things that happens is that they are extremely ",
    "image": "https://source.unsplash.com/rDEOVtE7vOs/1600x900",
    "tag": null
      },
  {
    "userId": 1,
    "id": 2,
    "write": "Henry Cavil",
    "date": "21/12/20",
    "time": "08:00AM",
    "title": " How to Write About Your Life? Start Here .",
    "body": " it is the time of  nseq are not criticize consumer happy that the pain or  nfugiat soothing pleasure forward or no discomfort may rejecting some  nWho, not being due, we may be able to open the man who did not, but there is no ",
    "image": "https://source.unsplash.com/WNoLnJo7tS8/1600x900",
    "tag": null
  },
  {
    "userId": 1,
    "id": 3,
    "write": "Katrina Taylor",
    "date": "24/12/20",
    "time": "06:49PM",
    "title": " How to Survive as a Freelancer in 2020 ",
    "body": " innocent, but the law  nvoluptatis blinded the election or the  nvoluptatis pains or prosecutors who is to pay nmolestiae and is willing to further or to and from the toil of an odious term ",
    "image": "https://source.unsplash.com/vMV6r4VRhJ8/1600x900",
    "tag": {
            "country": "British"
          }
  }
]

我正在使用 JSON 提取器提取所有值。但是我面临的 tags.country 问题是它不适用于所有数组项。我正在使用这个 JSON 路径 $.[*].tag.country 使用匹配号 -1,然后我的目标是在 for each 循环中使用它。但是由于国家/地区仅在 1 项中可用,我不确定如何将其与相应的项目联系起来。我可以编写一些代码,但只是探索是否有更简单的选项可用。

我想要总共 3 个国家实例,无论它是否有值我打算将默认值设置为“ Country-NotFound ”,然后在稍后的过程中使用这个值。

4

1 回答 1

0

我认为您无法使用 JSON Extractor 一次性实现它,因为JSONPath只会返回country属性不为空的值

我建议使用JSR223 PostProcessor和以下代码:

def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
0.upto(response.size() - 1, { index ->
    if (response.get(index).tag == null) {
        vars.put('tag_' + (index + 1), 'Country-NotFound')
    } else {
        vars.put('tag_' + (index + 1), response.get(index).tag.country)
    }
})

鉴于您的 JSON 响应,它应该生成以下 JMeter 变量:

tag_1=Country-NotFound
tag_2=Country-NotFound
tag_3=British   

适合使用 ForEach 控制器进行迭代

更多信息:

于 2020-06-29T15:37:40.327 回答