Home > database >  Remove a block from JSON payload using Groovy script
Remove a block from JSON payload using Groovy script

Time:03-24

Please find an example payload, where I am trying to remove one block based on the updated date. I am looking to get the message block where the updated date is less than a week from the current date.

[
  {
    "firstName": "person1",
    "lastName": "lname",
    "createdDate": "2021-11-18T03:08:50.000Z",
    "externalId": null,
    "id": "123",
    "updatedDate": "2022-03-18T19:33:28.792Z",
    "title": "XXXX",
    "email": "[email protected]",
    "enabled": true
  },
  {
    "firstName": "P2",
    "lastName": "lname2",
    "createdDate": "2021-10-26T19:12:16.000Z",
    "externalId": null,
    "id": "125",
    "updatedDate": "2022-03-01T18:01:19.762Z",
    "title": ".",
    "email": "[email protected]",
    "enabled": true
  }
]

Using the following code to get the desired result. The remove statement seems to be not removing the collection from body1, or I am dong something wrong here. Tried adding the body1 to the message body, is not working. Tried using the builder, this is giving a completely different error. Any help would be highly appreciated.

import com.sap.gateway.ip.core.customdev.util.Message; 
import java.util.HashMap; import groovy.json.*; 
import groovy.json.JsonSlurper;
import groovy.json.JsonBuilder

def Message processData(Message message) { 
    //Body 
    def body = message.getBody(java.lang.String) as String; 
    def body1 = new JsonSlurper().parseText(body) 
    def jsonOp 
    def builder = new JsonBuilder()  
    def today = new Date()
    def targetDate = today - 7
    pastweek = (targetDate.format("yyyy-MM-dd\'T\'HH:mm:ss'Z'"))
    body1.collect.eachWithIndex { it,index->
     if ( it.updatedDate < pastweek )
       {   
            it.remove(index)               
       }     
       else {
            builder {
            'firstName' it.firstName
            'lastName' it.lastName
            'email' it.email
            'updatedDate' it.updatedDate
            'enabled' it.enabled
        }   
       }
     }
    def finalJson = builder.toPrettyString()   
    message.setBody(finalJson.toString())
    return message;
}

CodePudding user response:

import groovy.json.*

def Message processData(Message message) { 
    def body = message.getBody(java.lang.String) as String
    def data = new JsonSlurper().parseText(body)
    def pastweek = (new Date()-7).format("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    data.removeAll{it.updatedDate < pastweek}
    message.setBody(new JsonBuilder(data).toPrettyString())
    return message
}
  • Related