cancel
Showing results for 
Search instead for 
Did you mean: 

Format json body by removing an object using Groovy in CPI

niyatijain2
Explorer
0 Kudos

Hello all,
I am having a json body which I need to format where there's an object called 'shipping_packages' which I need to remove but when I use the below code, I get null in the result.. Can anyone help me with this?
Input:

{
  "abxy": [
    {
      "abc": "123"
    }
  ],
  "shippingPackages": [
    {
      "def": "234",
      "hij": "456",
      "klm": {
        "nop": "678"
      }
    }
  ]
}<br>

and my desired output is:

{
  "abxy": [
    {
      "abc": "123"
    }
  ]
}<br>

and the code I am trying for which I am getting null is:

import com.sap.gateway.ip.core.customdev.util.Message;

import groovy.time.TimeCategory import java.util.HashMap;
import groovy.json.JsonSlurper;

import groovy.json.JsonBuilder def Message processData(Message message) {
    def body=message.getBody(String);
    def map=new JsonSlurper();
    def object=map.parseText(body) def builder=new JsonBuilder(object.shippingPackages) message.setBody(builder.toString()) return message;
}<br>
MortenWittrock
Active Contributor

Hi Nayati

Your JSON is a bit of a mess. Please try to 1) make sure it is valid (it isn't right now) and 2) format it for readability. The same goes for the code. That makes it a lot easier to answer the question.

Also: In your question you state that you want to remove the shippingPackages property, but the code seems to remove everything but the value of the shippingPackages property.

What should the payload look like after your script?

Regards,

Morten

View Entire Topic
Nikhil_Gursal
Participant
0 Kudos

Hi niyatijain2 ,

below groovy script will help you achieve target Json as per your requirement.

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def Message processData(Message message) {
    def body = message.getBody(String)
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper.parseText(body)
    
    // Keep only "abxy" data
    def abxyData = jsonObject.abxy
    
    // Create a new JSON object with only "abxy" data
    def newJsonObject = [abxy: abxyData]

    // Convert the new JSON object to a JSON string
    def jsonBuilder = new JsonBuilder(newJsonObject)
    def jsonString = jsonBuilder.toString()

    // Set the modified JSON string as the new message body
    message.setBody(jsonString)

    return message
}
Regards,Nikhil
niyatijain2
Explorer
0 Kudos

Thank you Nikhil,

but my original payload is not much like a simple payload as I have provided as it contains more 10+ properties with more objects inside as well so thank you for providing an answer but this won't help me passing the original body.

Regards,

Niyati Jain