Forum Discussion

shyne's avatar
shyne
Occasional Contributor
2 years ago
Solved

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 (tutorialspoint.com))

 

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) {
	log.info "=== KEY: " + item.toString() + " ==="

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

	if(keyValue =~ '^\\{.*\\}$') {
		log.info "This is an object"
	} else if (keyValue =~ '^\\[\\[.*\\]\\]$') {
		log.info "This is a object array"
	} else if (keyValue =~ '^\\[.*\\]$') {
		log.info "This is an array"
	} else {
		log.info "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: 1
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.