Skip to Content

How to remove root element in JSON after conversion in groovy script

Hi Experts,

How can we remove root element in JSON after conversion using groovy script in HCI.

After JSON Converter, it will become:

{
  "MT_Request": {
    "CORPID": "API1",
    "USERID": "User2",
    "DEBITACC": "000405002345",
    "CREDITACC": "000405001223",
    "IFSC": "SA12345 ",
    "AMOUNT": "7",
    "CURRENCY": "INR",
    "TXNTYPE": "RWS",
    "AGGRID": "1234",
    "PAYEENAME": "party",
    "UNIQUEID": "UNIQUE_ID",
    "AGGRNAME": "ABC",
    "URN": "Test1",
    "REMARKS": "Test Payload1"
  }
}

So, I want the output as below :

{
  "CORPID": "API1",
  "USERID": "User2",
  "DEBITACC": "000405002345",
  "CREDITACC": "000405001223",
  "IFSC": "SA12345 ",
  "AMOUNT": "7",
  "CURRENCY": "INR",
  "TXNTYPE": "RWS",
  "AGGRID": "1234",
  "PAYEENAME": "party",
  "UNIQUEID": "UNIQUE_ID",
  "AGGRNAME": "ABC",
  "URN": "Test1",
  "REMARKS": "Test Payload1"
}

When i am using one groovy script its working fine but all fields are shuffling.

Used Groovy script:

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

def Message processData(Messagemessage){
    def body =message.getBody(java.lang.String)asString
    def jsonParser =new JsonSlurper()
    def jsonObject = jsonParser.parseText(body)message.setBody(JsonOutput.toJson(jsonObject["MT_Request"]))returnmessage;}

I am getting shuffled output as below .

{
  "CORPID": "API1",
  "AGGRNAME": "ABC",
  "PAYEENAME": "party",
  "URN": "Test1",
  "CREDITACC": "000405001223",
  "DEBITACC": "000405002345",
  "REMARKS": "Test Payload1",
  "AMOUNT": "7",
  "UNIQUEID": "UNIQUE_ID ",
  "IFSC": "SA12345",
  "AGGRID": "1234",
  "TXNTYPE": "RWS",
  "CURRENCY": "INR",
  "USERID": "User2"
}

Thanks and Regards,

Md.Thouheed

Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

2 Answers

  • Dec 09, 2017 at 02:07 PM

    Hi Sriprasad,

    Thanks for quick response, i found the other solution also it's worked successfully.

    Just selected the suppress JSON Root Element check box.

    Thanks and Regards,

    Md.Thouheed

    Add comment
    10|10000 characters needed characters exceeded

  • Nov 24, 2017 at 07:18 AM

    Hello Md,

    Its known behavior of JSON parser.

    Use below code it should work ( if you just want to remove header node starting with MT*).

    import com.sap.gateway.ip.core.customdev.util.Message;
    import java.util.HashMap;
    
    def Message processData(Message message) {
    	
    	def body = message.getBody();
    	body = body.substring(body.indexOf('\n')+15);
      
    	def json_to_str=body.substring(1,body.length()- 2);  
    	message.setBody(json_to_str);
    	
    	return message;
    }
    

    Regards,

    Sriprasad Shivaram Bhat

    Add comment
    10|10000 characters needed characters exceeded