Search code examples
foreachjmeterjmeter-5.0foreach-loop-container

Foreach controller not working for Json data


I have below json

[
  {
   "id":  13059,
   "xid": "81f4278a53fe4c1a8d03346a34d76a47",
   "yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5a75"
  },
  {
    "id":  13059,
    "xid": "061ef5792e8f4603bb1f86c71e6fb16c",
    "yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5a56"
  },
  {
    "id":  13061,
    "xid": "4290987b25b34ffbb5b0329f1ab1b673",
    "yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-5dd4"
  },
  {
    "id":  13063,
    "xid": "57c4a2790aa44376be1e5215c5cb7ad0",
    "yid": "8cbefbadec52ced5:e4f6801:17c73aeaf21:-585e"
  }
]

Now I put the above json in global variable in JSR223 sampler

 vars.put("jsonVariable",JSON.stringify(aboveJson))

Now next I add "ForEach Controller" and add

   InputVariable Prefix = jsonVariable

   Output variable name = outVariable

Then I add another JSR223 sampler inside ForEach Controller and log below data

log.info(${outVariable})

But ForEach controller is not even executing for once. Please let me know where I did wrong


Solution

  • ForEach Controller isn't smart enough to parse your JSON structure, it iterates an individual set of JMeter Variables which looks like:

    var_1=foo
    var_2=bar
    etc.
    

    so depending on what you're trying to achieve you need to:

    1. In case if you want individual values of id, xid and/or yid - add 1 or more JSON Extractors and configure them to fetch the values from the response. Then use ForEach Controller and feed the variable from JSON Extractor to it

      enter image description here

    2. If you want to iterate JSON Objects instead you can use JSR223 PostProcessor and the following Groovy code:

      new groovy.json.JsonSlurper().parse(prev.getResponseData()).eachWithIndex { entry, int index ->
          vars.put('json_' + (index + 1), new groovy.json.JsonBuilder(entry).toString())
      }
      

      enter image description here