Search code examples
grailsgroovy

Json file parsing - Groovy


For our test data we are going to maintain the test data in JSON format, and below is the sample JSON file.

{
    "INV": [
        {
            "TestCaseID": "APL",
            "TestData": [
                {
                    "INVLabel": "Title",
                    "Controltype": "text",
                    "Inputvalues": "solid state device"
                },
                {
                    "INVLabel": "Inventor",
                    "Controltype": "search",
                    "Inputvalues": "Sabra-Anne Truesdale"
                }
            ]
        },
        {
            "TestCaseID": "APL1",
            "TestData": [
                {
                    "INVLabel": "Title",
                    "Controltype": "text",
                    "Inputvalues": " "
                },
                {
                    "INVLabel": "Inventor",
                    "Controltype": "search",
                    "Inputvalues": "jenifer"
                }
            ]
        }
    ]
}

using JsonSlurper how can I retrieve test data based on the test case id?. initially, I planned to convert the JSON into Map Object from that I tried. but it's not working as expected. can anyone please guide me to retrieve these values?


Solution

  • You can use a find() method on the INV node with a closure { it.TestCaseID == 'ID'} to get the first element from the list. Consider the following example that extracts the test data for the id APL1.

    import groovy.json.JsonSlurper
    
    def input = '''{
        "INV": [
            {
                "TestCaseID": "APL",
                "TestData": [
                    {
                        "INVLabel": "Title",
                        "Controltype": "text",
                        "Inputvalues": "solid state device"
                    },
                    {
                        "INVLabel": "Inventor",
                        "Controltype": "search",
                        "Inputvalues": "Sabra-Anne Truesdale"
                    }
                ]
            },
            {
                "TestCaseID": "APL1",
                "TestData": [
                    {
                        "INVLabel": "Title",
                        "Controltype": "text",
                        "Inputvalues": " "
                    },
                    {
                        "INVLabel": "Inventor",
                        "Controltype": "search",
                        "Inputvalues": "jenifer"
                    }
                ]
            }
        ]
    }'''
    
    def json = new JsonSlurper().parseText(input)
    
    def testData = json.INV.find { it.TestCaseID == 'APL1' }.TestData
    
    println testData
    

    Output:

    [[INVLabel:Title, Controltype:text, Inputvalues: ], [INVLabel:Inventor, Controltype:search, Inputvalues:jenifer]]