arraysgroovyjsonslurper

Groovy JSONSlurper to reformat JSON object into array


I've been spinning my wheels long enough on this so I'm hopeful for some help or pointers. I'm new to groovy and have been able to wade my way this far in, but am stuck here.

Using Groovy, given the following input JSON:

{
    "rates": {
        "USD": 3.39,
        "EUR": 1.00,
        "CAD": 1.31
    }
}

I want to convert each value within the rates object to an array, looking similar to the following. Ideally this script can handle 1-n rates. Notice that From_Curr is statically added to each array obj.

{
    "rates": [{
            "From_Curr": "GBP",
            "To_Curr": "USD",
            "Rate": 3.397
        }, {
            "From_Curr": "GBP",
            "To_Curr": "EUR",
            "Rate": 1.00
        }, {
            "From_Curr": "GBP",
            "To_Curr": "CAD",
            "Rate": 1.31
        }
    ]
}

I tried the following groovy, and I realize that because I'm not starting with a json array it isn't quite working out how I want.

def collectedRates = new JsonSlurper()
    .parseText(inputJson)
    .rates
    .collectEntries{["From_Curr":"GBP","To_Curr":it.key,"Rate":it.value]};

Solution

  • User tim_yates in comments pointed out my flaw-- use collect instead of collectEntries. Working snippet below Thanks!

    def collectedRates = new JsonSlurper()
        .parseText(inputJson)
        .rates
        .collect{["From_Curr":"GBP","To_Curr":it.key,"Rate":it.value]};