Q:

SoapUI JSON Parsing - Get Parent Node using Child value

I have a JSON response like below from SoapUI.
    {
    "-1":    {
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 1,
      "build": "",
      "projectKey": "TEST",
      "started": ""
    },
    "0":    {
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 2,
      "build": "",
      "projectKey": "BEST",
      "started": ""
    },
    "2":    {
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 3,
      "build": "",
      "projectKey": "WORST",
      "started": ""
    }
    }

My requirement is, I have to get the value/node "0" which has the projectkey="BEST" using JsonSurpler or Groovy Script Test Step. The projectkey is now under the node "0". Maybe it will be under "10" or "1000" or "-500". 
How to get the parent node using a child node value?

A:

There are different ways to achieve that. These are the simplest I can recollect now:
import groovy.json.JsonSlurper

String string = '''{
    "-1": {
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 1,
      "build": "",
      "projectKey": "TEST",
      "started": ""
    },
    "0":{
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 2,
      "build": "",
      "projectKey": "BEST",
      "started": ""
    },
    "2": {
      "startDate": "",
      "modifiedBy": "",
      "endDate": "",
      "projectId": 3,
      "build": "",
      "projectKey": "WORST",
      "started": ""
    }
}'''

def json = new JsonSlurper().parseText(string)

assert json.find { it.value?.projectKey == 'BEST' }?.key == '0'
assert json.findResult { k, v -> v?.projectKey == 'BEST' ? k : null } == '0'

This will find the first item which satisfies the condition. If you need all the items which satisfy the condition then use findAll or findResults accordingly.

