Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to Groovy with JsonSlurper and unknown "string"

I am writing a Grails/Groovy app and I have a JSON object with a "string" name (grommet and widget) inside the params member that can change. That is, next time it might be acme and zoom. Here is the JSON:

def jx = """{ 
    "job": "42",
    "params": {
        "grommet": {"name": "x", "data": "y"},
        "widget": { "name": "a", "data": "b"}
    } 
}"""

I am trying to figure out how to get the string grommet . Code so far:

def dalist = new JsonSlurper().parseText(jx)
println dalist.job     // Gives: 42
println dalist.params  // Gives: [grommet:[name:x, data:y], widget:[name:a, data:b]]
println dalist.params[0]  // Gives: null

Any idea how to get the string grommet? Iama going to keep hitting my head against a wall.

like image 483
rtfminc Avatar asked Jun 16 '12 04:06

rtfminc


3 Answers

The params key on the JSON object is associated with a JSON object, not an array, so you cannot access it by index. JsonSlurper maps JSON objects to Groovy Maps, so you can access params by its keys, which are strings, e.g. dalist.params.grommet, which will give you the map [name: 'x', data: 'y'].

To access the keys on the params you can do dalist.params.keySet(), which will give you the list ['grommet', 'widget']. If you are interested in just knowing params keys, that should do the trick. If you need to get the 'grommet' string for some reason, you can do it by accessing the first element on that list, i.e. dalist.params.keySet()[0], but i don't know why you would want to know that. And i'm not sure if it is guaranteed that the first key of that map will always be 'grommet', as JSON objects are unordered by the spec (from json.org: An object is an unordered set of name/value pairs), but, in turn, Groovy maps are ordered (the default implementation is LinkedHashMap)... so i would assume that the order is preserved when parsing JSON to the Groovy world, but i'd try not to rely on that particular behavior hehe.

like image 70
epidemian Avatar answered Nov 08 '22 05:11

epidemian


It's Map instance, try:

def params = dalist.params.entrySet() as List  // entrySet() returns Set, but it's easier to use it as a List
println params
println params.size()
println params[0]
println params[0].key
println params[0].value
like image 4
Igor Artamonov Avatar answered Nov 08 '22 05:11

Igor Artamonov


This might help you.

import groovy.json.JsonSlurper;
def jx='{"job":"42","params":{"grommet":{"name":"x","data":"y"},"widget":{"name":"a","data":"b"}}}'

def dalist = new JsonSlurper().parseText( jx )

assert dalist.params.getClass().name == "java.util.HashMap";
assert dalist.params.size() == 2;

def keys = dalist.params.collect{ a, b -> a}; // returns "[grommet, widget]"
assert !!dalist.params.get( "grommet" ) == true
like image 2
Larry Battle Avatar answered Nov 08 '22 07:11

Larry Battle