I need to implement a method that will scan a string of JSON for a particular targetField
and either return the value of that field (if it exists), or null
(if it doesn't):
// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'fizz') => 'buzz'
// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'foo') => null
String extractFieldValue(String json, String targetField) {
// ...
}
This solution has to be recursive and work at any nesting-level in the (hierarchical) JSON string. Also it needs to work for JSON arrays as well.
My best attempt so far:
String extractFieldValue(String json, String targetField) {
def slurper = new JsonSlurper()
def jsonMap = slurper.parseText(json)
jsonMap."${targetField}"
}
This only works on top-level (non-nested) JSON fields. I asked the Google Gods how to use JsonSlurper
recursively, but couldn't find anything useful. Any ideas here?