Mahbub Rahman - 11 months ago 119
Groovy Question

# Groovy: Parsing JSON file

I am quite new to Groovy and I am parsing a JSON file with following code:

void getItemData()
{
def jsonSlurper = new JsonSlurper()
data.TESTS.each{println  it.MEMBER_ID}
}


And I am getting printed properly the value of MEMBER_ID.

I want to Parameterize the above function like:

void getItemData(String item)
{
...
}


so that I can call this function with the desired item I want. For example: I want the MEMBER_ADDRESS. I want to call the function like:

getItemData("MEMBER_ADDRESS")


Now How I should change the statement:

data.TESTS.each{println  it.MEMBER_ID}


I tried with

it.${item}  and some other ways not working. Please teach me how to do it. My JSON file is like below: { "TESTS": [ { "MEMBER_ID": "my name", "MEMBER_ADDRESS": "foobarbaz", } ] }  Answer Source You need to add quotes around ${item} like:

import groovy.json.*

void getItemData(String item) {
def jsonSlurper = new JsonSlurper()