Home > other >  Groovy: Retrieve a value from a JSON based on an object
Groovy: Retrieve a value from a JSON based on an object

Time:09-29

So I have a JSON that looks like this

{
   "_embedded" : {
      "userTaskDtoList" : [
         {
            "userTaskId" : 8,
            "userTaskDefinitionId" : "JJG",
            "userRoleId" : 8,
            "workflowId" : 9,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:04:37Z",
            "dueDateFormatted" : "Tomorrow 09:04",
            "acknowledge" : false,
            "key" : 8,
         },
         {
            "userTaskId" : 10,
            "userTaskDefinitionId" : "JJP",
            "userRoleId" : 8,
            "workflowId" : 11,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:06:44Z",
            "dueDateFormatted" : "Tomorrow 09:06",
            "acknowledge" : false,
            "key" : 10,
         },
         {
            "userTaskId" : 12,
            "userTaskDefinitionId" : "JJD",
            "userRoleId" : 8,
            "workflowId" : 13,
            "criticality" : "MEDIUM",
            **"dueDate"** : "2021-09-29T09:59:07Z",
            "dueDateFormatted" : "Tomorrow 09:59",
            "acknowledge" : false,
            "key" : 12,
         }
      ]
   }
}

It's a response from a REST request. What I need is to extract the data of key "dueDate" ONLY from a specific object and make some validations with it. I'm trying to use Groovy to resolve this.

The only thing I've managed to do is this:

import groovy.json.*

def response = context.expand( '${user tasks#Response}' )
def data = new JsonSlurper().parseText(response)

idValue = data._embedded.userTaskDtoList.dueDate

Which returns all 3 of the values from the "dueDate" key in the response. I was thinking that maybe I can interact with a certain object based on another key, for instance let's say I retrieve only the value from the "dueDate" key, that is part of the object with "userTaskId" : 12. How could I do this?

Any help would be greatly appreciated.

CodePudding user response:

You can find the record of interest, then just grab the dueDate from that

data._embedded.userTaskDtoList.find { it.userTaskId == 12 }.dueDate
  • Related