Skip to Content

How to remove fields in JSON after conversion in groovy script

Remove Field in JSON after conversion

{

"element":

[

{"name:lastname:firstname":" ",

"gender":"M",

"country":"US",

"id":"1"},

]

}

My desired JSON message is

{

"element":

[

{"":" ",

"gender":"M",

"country":"US",

"id":"1"},

]

}

i am using this script code:

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["name:lastname:firstname"]))

returnmessage;

}


But field is not removing please help me to remove field from JSON Structure

Regards,

Naveen

Add a comment
10|10000 characters needed characters exceeded

Related questions

1 Answer

  • Best Answer
    Posted on Sep 24, 2018 at 11:10 AM

    Hello Naveen,

    Below will work.

    Script:

    import com.sap.gateway.ip.core.customdev.util.Message;
    import java.util.HashMap;
    import groovy.json.JsonSlurper;
    import groovy.json.JsonOutput;
    import groovy.json.*;
    
    def Message processData(Message message)
     {
    	
        def body =message.getBody();
        def jsonSlurper = new JsonSlurper();
        def list = jsonSlurper.parseText(body);    
        list.element.each{
           it.remove('name:lastname:firstname');       
            }
        def jsonOP = JsonOutput.toJson(list)
        message.setBody(jsonOP);
        return message;
    }

    Input Data:

    {
        "element":
        [
            {
                "name:lastname:firstname": " ",
                "gender": "M",
                "country": "US",
                "id": "1"
            },
            {
                "name:lastname:firstname": " ",
                "gender": "M",
                "country": "US",
                "id": "2"
            }
        ]
    }
    

    Regards,

    Sriprasad Shivaram Bhat

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.