Mahbub Rahman Mahbub Rahman - 2 months ago 26
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()
def reader = new BufferedReader(new InputStreamReader(new FileInputStream("data.json"),"UTF-8"));
data = jsonSlurper.parse(reader);
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

You need to add quotes around ${item} like:

import groovy.json.*

void getItemData(String item) {
    def jsonSlurper = new JsonSlurper()
    def reader = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/json"),"UTF-8"))
    data = jsonSlurper.parse(reader)  
    data.TESTS.each { println  it."$item" }
}

getItemData("MEMBER_ADDRESS")
Comments