Groovy: Parsing JSON file

18,479

Solution 1

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

Solution 2

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")
Share:
18,479
Mahbub Rahman
Author by

Mahbub Rahman

Updated on July 29, 2022

Comments

  • Mahbub Rahman
    Mahbub Rahman almost 2 years

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