Nicolas Raoul Nicolas Raoul - 8 months ago 46
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
syntax, because the number would be hard-coded.

How to get the color?


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'