8

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",
         }
    ]
}
Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44

2 Answers2

15

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")
Sorter
  • 9,704
  • 6
  • 64
  • 74
6

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")
Gergely Toth
  • 6,638
  • 2
  • 38
  • 40