Filtering/capture the specific index of array from Json

Try to filter/capture JSon output from selective index. Fieldid values changes with every build, What do not change is fieldName": "TX.Sessionval.cost" . Need to filter out the whole stringval and save into variable

fieldName": "TX.Sessionval.cost"
[
  {
   "Fieldid": "Fieldid/112",
    "fieldName": "TX.Sessionval.cost",
    "stringval": "jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name"
  }
]

tried def slurper = new JsonSlurper() def result = slurper.parseText(response.getResponseBodyContent()) def newf = result.findAll { it.contains("TX.Sessionval.cost") } getting groovy.lang.MissingMethodException: No signature of method: java.util.LinkedHashMap$Entry.contains()

In Postman it works fine with

postman.setEnvironmentVariable("Stdid", jsonData.newFields[112].stringValue) 

The following code worked for me. Please find a difference from your code.

import groovy.json.JsonSlurper

def text = """
[
  {
   "Fieldid": "Fieldid/foo",
    "fieldName": "bar",
    "stringval": "baz"
  },
  {
   "Fieldid": "Fieldid/112",
    "fieldName": "TX.Sessionval.cost",
    "stringval": "jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name"
  }
]
"""

def slurper = new JsonSlurper() 

def result = slurper.parseText(text) 

def newf = result.findAll { Map map ->
	map.get("fieldName").contains("TX.Sessionval.cost") }
//     ^^^^^^^^^^^^^^^^^

println newf
1 Like

@kazurayam result Gives me[[fieldName:TX.Sessionval.cost, id:newField/128, "stringval":"jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name"]]` how to get the string values. part one is done

Part 2 is ->
how to get the stringvalue “stringval”: "jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name" only ?

further used split()

import groovy.json.JsonSlurper

def text = """
[
  {
   "Fieldid": "Fieldid/112",
    "fieldName": "TX.Sessionval.cost",
    "stringval": "jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name"
  }
]
"""
def slurper = new JsonSlurper() 
def result = slurper.parseText(text) 
def newf = result.findAll { Map map ->
	map.get("fieldName").contains("TX.Sessionval.cost") }

println newf                           // [[Fieldid:Fieldid/112, fieldName:TX.Sessionval.cost, stringval:jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name]]
println newf[0]                        // [Fieldid:Fieldid/112, fieldName:TX.Sessionval.cost, stringval:jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name]
println newf[0].stringval              // jklah-dw-4c8d-8320-das313s3ASsda|000725N8WuUrfwAS7alP|banker_name
println newf[0].Fieldid                // Fieldid/112
println newf[0].Fieldid.split("/")     // [Fieldid,112]
println newf[0].Fieldid.split("/")[1]  // 112

Just for your interest, a material to learn how to find elements in Collections in Groovy:

1 Like

@kazurayam Yeah did that part too. Thanks …its very helpful