简体   繁体   中英

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?

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.

Anyone in similar situation as me trying to import a JSON file at runtime. I used Active Choice parameter to solve my problem. There is an option to write groovy script in Active Choice Parameter plugin of Jenkins. There i have written below code to import a JSON file to achieve desired results.

import groovy.json.JsonSlurper
def inputFile = new File('.//TestSuitesJ.json')
def inputJSON = new JsonSlurper().parse(inputFile)
def keys = inputJSON.keySet() as List

Thanks @sensei to help me learn groovy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM