Home > database >  Groovy: json get value of id based on child value
Groovy: json get value of id based on child value

Time:02-10

I have a json as below:

[
   {
      "id":6619137,
      "oid":"6fykq37gm60x",
      "key":{
         "key":"6619137"
      },
      "name":"Prod",
      "planKey":{
         "key":"PDP"
      },
      "environments":[
         {
            "id":6225923,
            "key":{
               "key":"6619137-6225923"
            },
            "name":"Production",
            "deploymentProjectId":6619137,
         }
      ],
   },
   {
      "id":6619138,
      "oid":"6fykq37gm60y",
      "key":{
         "key":"6619138"
      },
      "name":"QA",
      "planKey":{
         "key":"QDP"
      },
      "environments":[
         {
            "id":6225924,
            "key":{
               "key":"6619138-6225924"
            },
            "name":"QA",
            "deploymentProjectId":6619138,
         }
      ],
   },
]

I can use the below code to extract the value of id and environments.id based on the name value. projectID will give 6619137 and environmentID will give 6225923

def e = json.planKey.find{it.name=='Prod'}
def projectID = e.id
def environmentID = e.environments[0].id

However, when I try to extract the value of id and environments.id based on the plankey.key value (e.g. PDP or QDP), using the same format above returns me an error of java.lang.NullPointerException: Cannot get property 'id' on null object at Script60.run(Script60.groovy:52)

def e = json.planKey.find{it.planKey=='{key=PDP}'}
def projectID = e.id
def environmentID = e.environments[0].id

Is there a way I can get the projectID with the plankey key value?

CodePudding user response:

Think of your JSON object as a key/value map with multiple levels. There is no such item as

json.planKey.find{it.planKey=='{key=PDP}'}

However, you can find with values at any level, like this:

def e = json.planKey.find{it.planKey.key == "PDP"}

If you have a structure where planKey may not exist, or it doesn't always have key, that's a bit different, but from your question it sounds like that's not the case here.

  • Related