Search code examples
jsongroovyjsonslurper

Get value of variable from json using jsonslurper


I have the following JSON code:

{  
"TIMESTAMP":"2017-05-26-20.22.40.016000",
"dateTime":"2017-05-26H-20.22.4",
"AMUCCY1":"ADP",
"rates":[  
   {  
      "AMUCCY2":"AED",
      "AMURAT":"1.000000000",
      "AMUNXRT":0
  },
  {  
     "AMUCCY2":"AFA",
     "AMURAT":"1.000000000",
     "AMUNXRT":0
  },
  {  
     "AMUCCY2":"ALL",
     "AMURAT":"1.000000000",
     "AMUNXRT":0
  },
  {  
     "AMUCCY2":"AMD",
     "AMURAT":"1.000000000",
     "AMUNXRT":0
  }
 ]
}

Is there quick way in groovy where I could loop through each of the 'rates' and get the value of, let's say 'AMUCCY2' ?

I tried doing this code:

jsonObj.rates.each {
    def toCurrencyMap = jsonObj.rates.AMUCCY2
    LOG.info "${toCurrencyMap}"
}

but the toCurrencyMap returns an array of all four values of this field. I only want to get each value; not all.

Any suggestions is appreciated.


Solution

  • You can try this:

    jsonObj.rates.each {
      println it.AMUCCY2
    }
    

    If you want list / array:

    def result = jsonObj.rates.collect { it.AMUCCY2 }
    println result