Nicolas Raoul Nicolas Raoul - 1 year ago 88
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?

Answer Source

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'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download