Get JSON keys' names in Groovy

During JMeter testing I have to get an array of JSON first-level keys' names. I.e. from JSON like

{
    "name": "Sally",
    "address": {
        "country": "Kuba",
        "city": "Havana"
    }
}

I want to get

<name, address>

I'm using Groovy & JsonSlurper, but have no idea, how to get this.

Upvotes: 2

Views: 6578

Answers (2)

Dmitri T
Dmitri T

Reputation: 167992

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

    new groovy.json.JsonSlurper().parse(prev.getResponseData()).keySet().eachWithIndex { key, index ->
        log.info('Key ' + index + ': ' + key)
    }
    

Explanation:

  • prev is an instance of SampleResult which provides access to the parent Sampler result object
  • in your case JsonSlurper returns "slurped" JSON as a LazyMap so you can access its keys by calling keySet() function

References:

Upvotes: 0

lffloyd
lffloyd

Reputation: 333

If you already have a JSON object, you can do:

println jsonObject.keySet()

If you don't, you will need to create one. With the stringfied JSON you can do:

def json =  '{"name": "Sally","address": {"country": "Kuba","city": "Havana"}}'
def jsonObject = new JsonSlurper().parseText(json)
println jsonObject.keySet() 

Upvotes: 4

Related Questions