Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help to read a json file using groovy and Jenkins

I am facing some issues reading a JSON file. I am using Jenkins Active Choice Parameter to read value from a JSON file via groovy script. This is how my JSON file look.

{
  "smoke": "Test1.js",
  "default": "Test2.js"
}

I want my groovy script to print out smoke and default. Below is what my groovy code look like.

import groovy.json.JsonSlurper
def inputFile = new File(".\TestSuitesJ.json")
def InputJSON = new JsonSlurper().parseText(inputFile)
InputJson.each
{
return[
key
]
}

Above code is not working for me. Can someone please suggest a better groovy way?

like image 617
NewWorld Avatar asked Sep 29 '16 20:09

NewWorld


People also ask

How do I use Groovy in Jenkins?

Usage. To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.

Does Jenkins support Groovy?

Jenkins features a Groovy script console which allows one to run arbitrary Groovy scripts within the Jenkins controller runtime or in the runtime on agents. It is very important to understand all of the following points because it affects the integrity of your Jenkins installation.


1 Answers

You really should read the groovy dev kit page, and this in particular.

Because in your case parseText() returns a LazyMap instance, the it variable you're getting in your each closure represents a Map.Entry instance. So you could println it.key to get what you want.

A more groovy way would be:

inputJson.each { k, v ->
  println k
}

In which case groovy passes your closure the key (k) and the value (v) for every element in the map.

like image 121
sensei Avatar answered Nov 15 '22 09:11

sensei