def parsed = new JsonSlurper().parseText(json)
assert == 'group1'
assert parsed.status.partitions.find { it.topic == 'topic1' && it.partition == 
0 }?.end?.lag == 0

Putting your JSON into a string variable “json”, the above asserts pass. The 
group was not put into a find because the status field is an object, not an 
array, so you’d check it with a normal if statement rather than find. The 
result is the end.lag field of the first partition found matching the topic and 
partition number, or null if no partition was found, or the first partition 
found does not have the field, or if the field exists but is null.

If you want to limit only to partitions with lag defined, you can change the 
search accordingly:

assert parsed.status.partitions.find { it.topic == 'topic1' && it.partition == 
0 && it.end?.lag != null }?.end?.lag == 0


From: Brandon Metcalf <>
Sent: Tuesday, November 27, 2018 12:20 PM
Subject: finding value of key at same level as another key


I have the following json

  "status": {
    "group": "group1",
    "partitions": [
        "topic": "topic1",
        "partition": 0,
        "start": {
          "offset": 0,
          "timestamp": 1543337772415,
          "lag": 0,
          "max_offset": 0
        "end": {
          "offset": 0,
          "timestamp": 1543337812000,
          "lag": 0,
          "max_offset": 0

I'm looking for a way in groovy to find the value of status.partitions.end.lag 
when I know the values of, status.partitions.topic and 
status.partitions.partition?  I may need to rethink my approach to how I think 
I should parse this json, but hopefully there is an easy way to do this.

Also, there can be multiple levels of the values that I know.  Just showing one 
for simplicity.


Reply via email to