Ask a Question

Groovy JSON value types

New Contributor

Groovy JSON value types

I'm using Groovy to loop through a JSON document returned by an API and will need to act / respond differently depending on the JSON value type. e.g. is the value an array or an object.


The code below uses regex and works ok, but I'm sure there's a better way.

(Looking at Groovy list methods but nothing obvious to me Groovy - Lists (


import groovy.json.*

def myJsonString = """
    "a": "value1",
    "b": {
        "b1": "object value1",
        "b2": "object value2"
    "c": [
        {"c1": "object array value1"},
        {"c2": "object array value2"}
    "d": ["array value1", "array value2"],
    "e": null,
    "f": 1,
    "g": true
def myJson = new JsonSlurper().setType(JsonParserType.LAX).parseText(myJsonString)

def myJsonKeys = myJson.collect{"${it.key}"}

for(item in myJsonKeys) { "=== KEY: " + item.toString() + " ==="

	def keyValue = myJson.get(item.toString()).toString() keyValue

	if(keyValue =~ '^\\{.*\\}$') { "This is an object"
	} else if (keyValue =~ '^\\[\\[.*\\]\\]$') { "This is a object array"
	} else if (keyValue =~ '^\\[.*\\]$') { "This is an array"
	} else { "This is a key value pair"

the output is 

INFO: === KEY: a ===
INFO: value1
INFO: This is a key value pair
INFO: === KEY: b ===
INFO: {b2=object value2, b1=object value1}
INFO: This is an object
INFO: === KEY: c ===
INFO: [[c1:object array value1], [c2:object array value2]]
INFO: This is a object array
INFO: === KEY: d ===
INFO: [array value1, array value2]
INFO: This is an array
INFO: === KEY: e ===
INFO: null
INFO: This is a key value pair
INFO: === KEY: f ===
INFO: This is a key value pair
INFO: === KEY: g ===
INFO: true
INFO: This is a key value pair

 (boolean / null / integers don't really concern me for this, mainly if its an array object or object.)


Any pointers appreciated. Thanks.

New Contributor
Showing results for 
Search instead for 
Did you mean: