For some integration scenarios, especially those involving Web APIs, JavaScript might be a more familiar choice than Groovy. SAP CPI supports a JavaScript engine, which you can use to process JSON payloads. The built-in 'JSON' object makes it incredibly easy to convert between JSON strings and JavaScript objects.
Key JavaScript Methods:
- JSON.parse(): Converts a JSON string into a JavaScript object. This is the first step for reading and manipulating data from an incoming JSON payload.
- JSON.stringify(): Converts a JavaScript object back into a JSON string. This is used to prepare the data for a subsequent step in the integration flow.
Example JSON Payload:
{
"orderId": "ORD12345",
"customer": {
"name": "Jane Doe",
"address": {
"city": "London",
"country": "GB"
}
},
"status": "New"
}
Example JavaScript ('.js') Script:
importClass(com.sap.gateway.ip.core.customdev.util.Message);
function processData(message) {
//Body
var body = message.getBody(java.lang.String);
var jsonObject = JSON.parse(body);
// Access and modify a value
jsonObject.status = "In Progress";
jsonObject.customer.address.city = "Greater London";
// Set a message header from the data
message.setHeader("OrderId", jsonObject.orderId);
// Stringify the object back to a JSON string and set the message body
var newBody = JSON.stringify(jsonObject);
message.setBody(newBody);
return message;
}
Using these two methods, you can seamlessly read and write JSON data within your JavaScript steps, enabling powerful transformations and data enrichments.