JSON to Groovy with JsonSlurper and unknown "string"
grails, groovy, json
Solution
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.
Problem
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.