Mahbub Rahman
Mahbub Rahman

Reputation: 1343

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",
         }
    ]
}

Upvotes: 8

Views: 22365

Answers (2)

Sorter
Sorter

Reputation: 10220

Those here from google, looking for an answer to parse JSON File.

void getItemData(String item) {
    def jsonSlurper = new JsonSlurper()
    def data = jsonSlurper.parseText(new File("data.json").text)
    println data.TESTS.each{ println it["$item"] }  
}

getItemData("MEMBER_ADDRESS")

Upvotes: 15

Gergely Toth
Gergely Toth

Reputation: 6977

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")

Upvotes: 6

Related Questions