Search code examples
groovy

Append element of JSON object in Groovy script


  • What I am trying to achieve, details of my goal:

I would like to append three elements of my json object in Groovy.

I have this json:

[
  {
    "product": "banana",
    "from": "India",
    "price": "42"
  },
  {
    "product": "orange",
    "color": "Spain",
    "price": "5"
  }
]

which is from :

def jsonParser = new JsonSlurper()
def data = jsonParser.parseText(filedata)
println(data)
return data.product
  • Describe my expected result:

I would like to return the appended triplet string banana-India-42 and orange-Spain-5 etc.

  • Describe my actual result:

As of right now, with data.product, I am successfully seeing banana and orange

With data.from, I am successfully seeing India and Spain

  • What I have tried:

I tried the following:

def jsonParser = new JsonSlurper()
def data = jsonParser.parseText(filedata)
println(data)
return data.product + data.from + data.price

Unfortunately, this is not returning the concatenated string.

  • Question

How to return the appended string of the json?


Solution

  • import groovy.json.*
    
    def filedata = '''
    [
      {
        "product": "banana",
        "from": "India",
        "price": "42"
      },
      {
        "product": "orange",
        "from": "Spain",
        "price": "5"
      }
    ]
    '''
    
    def jsonParser = new JsonSlurper()
    def data = jsonParser.parseText(filedata)
    return data.collect{"${it.product}-${it.from}-${it.price}"}.join(' ')
    

    this code returns banana-India-42 orange-Spain-5