lucianojs
lucianojs

Reputation: 175

How to manipulate json data in Jmeter

In a Jmeter Script, I need to process a http response e manipulate a json for send in next request, because actually this manipulation occurs in a Angular client.

My Http reponse:

[
   {
      "function":"nameA",
      "rast":"F1",
      "tag":"EE",
      "probs":"0,987"
   },
   {
      "function":"nameB",
      "rast":"F2",
      "tag":"SE",
      "probs":"0,852"
   },
   {
      "function":"nameC",
      "rast":"F3",
      "tag":"CE",
      "probs":"0,754"
   }
]

I need convert the result in json bellow to post in next request:

[
   {
      "function":"nameA",
      "rast":"F1",
      "type":{
         "name":"EE"
      },
      "id":"alpha"
   },
   {
      "function":"nameB",
      "rast":"F2",
      "type":{
         "name":"SE"
      },
      "id":"alpha"
   },
   {
      "function":"nameC",
      "rast":"F3",
      "type":{
         "name":"CE"
      },
      "id":"alpha"
   }
]

I filter the response with this JSON Extractor:

[*].["function", "rast", "tag"]

But now I need to solve other problems:

  1. Add an id attribute (same for all functions)

  2. Add an object with the name type.

  3. Move the tag attribute into the object called type.

  4. Rename the tag attribute to the name.

Upvotes: 1

Views: 1446

Answers (1)

Dmitri T
Dmitri T

Reputation: 168217

  1. Add JSR223 PostProcessor as a child of the request which returns the original JSON
  2. Put the following code into "Script" area:

    def json = new groovy.json.JsonSlurper().parse(prev.getResponseData()).each { entry ->
        entry << [type: [name: entry.get('tag')]]
        entry.remove('tag')
        entry.remove('probs')
        entry.put('id', 'alpha')
    }
    def newJson = new groovy.json.JsonBuilder(json).toPrettyString()
    log.info(newJson)
    
  3. That's it, you should see the generated JSON in jmeter.log file.

    JSR223 PostProcessor manupulate JSON

    If you need to have it in a JMeter Variable add the next line to the end of your script:

    vars.put('newJson', newJson)
    

    and you will be able to access generated value as ${newJson} where required

More information:

Upvotes: 4

Related Questions