JSON before Groovy with JsonSlurper and an unknown string

I am writing a Grails / Groovy application and I have a JSON object with a string name ( grommet and widget ) inside the parameters which may change. That is, next time it can be acme and scale . 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 a grommet string. 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 grommet string? The pit will continue to bang its head against the wall.

+7
source share
3 answers

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

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

+9
source

He is a Map instance, try:

 def params = dalist.params.entrySet() as List // entrySet() returns Set, but it easier to use it as a List println params println params.size() println params[0] println params[0].key println params[0].value 
+4
source

This can 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 
+2
source

All Articles