NewWorld NewWorld - 16 days ago 5
JSON Question

Using JSONSlurper to pass second level of JSON in list

I am using Groovy and JSON Slurper in one of my Jenkins plugins.
Below is the code i am using.

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


This is how my test suite is defined:

{
"Website1": {
"smoke": "spec1.js",
"default": "spec2.js"
},
"Website2": {
"smoke":
["spec1.js",
"spec2.js",
"spec3.js"],
"default":
["spec1.js",
"spec5.js"],
"TestSuite2":
["spec1.js"]
}
}


Currently my list contains values as below if i use above code.


Website1 Website2


However I want it to contain value as below if i select Website2:


smoke default Testsuite2


Can someone please suggest a way? I tried below code but it is not working.

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

Answer

Try this way:

import groovy.json.JsonSlurper

def input = '''{
  "Website1": {
     "smoke": "spec1.js",
     "default": "spec2.js"
  },
  "Website2": {
     "smoke": 
        ["spec1.js",
         "spec2.js",
         "spec3.js"],
     "default": 
        ["spec1.js",
         "spec5.js"],
      "TestSuite2":
        ["spec1.js"]
    }
}'''

def inputJSON = new JsonSlurper().parseText(input)
def keys = inputJSON.Website2.keySet()
Comments