Nicolas Raoul Nicolas Raoul - 2 months ago 15
Groovy Question

Get JSON children of single node with random name in Groovy

In Groovy (not Grails), I want to get the color of such an item:

{
"8436": {
"color": "red",
}
}


The "8436" number is dynamic, but there is always only one.

I can't use JsonSlurper's
json.8436.color
syntax, because the number would be hard-coded.

How to get the color?

Answer

Another option, given:

def jsonStr = '''{
    "8436": {
        "color": "red",
    }
}'''

You could do:

import groovy.json.JsonSlurper

def json = new JsonSlurper().parseText(jsonStr)

def (rootKey, color) = json.findResult { k, v -> [k, v.color] }

assert rootKey == '8436'
assert color == 'red'