Skip to Content
Technical Articles
Author's profile photo Alexandre Rezende

How to remove null and empty fields from a JSON in SAP CPI

Hey guys,

After a long time without writing here I decided to take a few minutes to share some code that I recently used in a project and that I couldn’t find here in the community.

Basically, the code I’m going to share has a simple and highly requested functionality in some projects, cleaning JSON messages, removing null and blank fields (Ex. “field” : “” or “field” : null.).


import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def Message processData(Message message) {
    def body = message.getBody(String.class)
    def jsonSlurper = new JsonSlurper()
    def jsonObject = jsonSlurper.parseText(body)
    def cleanedObject = removeEmptyFields(jsonObject)
    def jsonBuilder = new JsonBuilder(cleanedObject)
    return message

def removeEmptyFields(def object) {
    if (object instanceof Map) {
        object.entrySet().removeAll { it.value == null || (it.value instanceof String && it.value.trim() == "") }
        object.collectEntries { [it.key, removeEmptyFields(it.value)] }
    } else if (object instanceof List) {
        object.collect { removeEmptyFields(it) }.findAll { it != null }
    } else {


Now let’s test it, which is very simple as below:



That’s it guys, glad I helped you and comment if you’re using the code in your projects.












Assigned Tags

      1 Comment
      You must be Logged on to comment or reply to a post.
      Author's profile photo Raul Vega
      Raul Vega

      Thanks Alexandre! I will help to do more efficient the transmission of information.