groovyjenkins-pipeline

In Groovy, how can I pass a JSON-formatted string to a function so the function treats it as JSON?


In a Jenkins pipeline, I executed an AWS command that gave me an array of JSONs, like this


def jsonArray = readJSON text: sh(returnStdout: true,
                                  script: "aws command sub-command ...")

and if I print jsonArray I get

{
  "SomeAJsonArray": [
    {
      "key1": "valueA",
      "key2": "valueB",
      "key3": "valueC"
    },
    {
      "key1": "valueX",
      "key2": "valueY",
      "key3": "valueZ"
    },
    // more json
  ]
}

Now I process the above output, and only store the JSONs that meet a criteria, like this

def processedJsonArray = []
jsonArray.SomeJsonArray.each {
  if (it.key1.contains("valueX")) {
    processedJsonArray.add(it)
  }
}

and if I print the elements of processedJsonArray, I get

processedJsonArray.each {
  println it
}

Output:
{"key1":"valueX","key2":"valueY","key3":"valueZ"}

which is what I expect, correct?

Now If I pass the elements of processedJsonArray to a function, and print the passed-in value in the function, I don't get a JSON string.

processedJsonArray.each {
  processJsonString(it)
}

// Called function
def processJsonString(final def jsonString) {
  println jsonString
}

Output:
[key1:valueX, key2:valueY, key3:valueZ]

Why is this? What is the correct way to do this so I also get this

{"key1":"valueX","key2":"valueY","key3":"valueZ"}

in the called function? Thanks!


Solution

  • readJSON step converts json string to an array/map representation.

    You can check the type of the parsed object by calling println jsonArray.getClass()

    To convert parsed object back to a json string use writeJSON step

    processedJsonArray.each {
      def jsonString = writeJSON json:it, returnText:true // converts `it` to a json string 
      processJsonString( jsonString )
    }
    
    // Called function
    def processJsonString(String jsonString) {
      println jsonString
    }