cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

JSON Message to change field value to null via Groovy Script

ZTK196
Explorer
0 Kudos
609

Hello, I'm still new to groovy scripting and I would like to achieve the following output.

Example

Input:

 

{
	"Book": {
		"Title": {
			"@nil": "true"
		},
		"Author": {
			"@nil": "true"
		},
		"year": "1960",
		"isbn": "9780061120084"
	}
}

 

Output:

 

	{
		"Book": {
			"Title":null,
			"Author": null,
			"year": "1960",
			"isbn": "9780061120084"
		}
	}

 

I need to change all the fields that has value = {"@nil": "true"} to null. How can I achieve this via groovy script? would really appreciate your help on this. Thank you!

Accepted Solutions (1)

Accepted Solutions (1)

robertot4s
Contributor

Hi @ZTK196

Work with JSON in Groovy is easy with the classes:

import groovy.json.JsonSlurper -> Process a JSON file
import groovy.json.JsonOutput -> Generate a new JSON file
 
Here you have the code for your example:
 
import com.sap.gateway.ip.core.customdev.util.Message;
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def Message processData(Message message) {
   
    def body = message.getBody(java.lang.String);
    def slurper = new groovy.json.JsonSlurper()
    def jsonInput = slurper.parseText(body)
   
    def transformedJson = [
    Book: [
        Title: convertNil(jsonInput.Book.Title),
        Author: convertNil(jsonInput.Book.Author),
        year: convertNil(jsonInput.Book.year),
        isbn: convertNil(jsonInput.Book.isbn)
    ]
]

    def outputJson = JsonOutput.prettyPrint(JsonOutput.toJson(transformedJson))
           
    message.setBody(outputJson);
    return message;
}

def convertNil(obj) {
    if (obj instanceof Map && obj.containsKey('@nil')) {
        return obj['@nil'] == "true" ? null : obj['@nil']
    }
    return obj
}
 
Hope it helps.
Regards,
Roberto
ZTK196
Explorer

Hi @robertot4s,

I used this script instead since they have common values. 

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

def Message processData(Message message) {

    def body = message.getBody(java.lang.String);
    body = body.replaceAll(/\{\s*"@nil":\s*"true"\s*\}/, 'null');
    
    message.setBody(body);
    
    // Set Content-Type
	message.setHeader("Content-Type","application/json");
	
    return message;
}

Still, Thank for your inputs, much appreciated. 

Answers (0)