Search code examples
muledataweavemulesoftmule4

Array in payload is string, need to coerce to array type (DataWeave)


I have a payload I'm receiving from debezium/kafka as "reasons": "[7,10,9]" with the array as a string.

I need to filter the array to extract when the item is 10 or 11. Since the array is actually a string in the payload I need to coerce it to an array to filter.

This is my current solution, but I feel there has to be a more efficient way:

%dw 2.0
output application/json
var data = payload.payload.after
var reasons = data.reasons replace "[" with "" replace "]" with "" splitBy  "," filter ((num, numIndex) -> num != "10" and num != "11")
---
{
"dnsType": if (dnsType[0] == "11") "clinical" else if (dnsType[0] == "10") "non-clinical" else ""
}

Solution

  • If the string content is compatible with a JSON array then you can use the read() function to let DataWeave parse it for you.

    Example read(data.reasons,"application/json")