-1

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 ""
}
aled
  • 21,330
  • 3
  • 27
  • 34
Matt P
  • 147
  • 1
  • 6

1 Answers1

2

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")

aled
  • 21,330
  • 3
  • 27
  • 34
  • Thanks! Would it make sense to parse the entire payload to JSON? Would the same method work? – Matt P Aug 29 '22 at 13:49
  • No, `read` needs a string. It won't if the input is a JSON itself. – Harshank Bansal Aug 29 '22 at 14:30
  • If the input is a JSON DataWeave already parsed it and it is a DataWeave object in memory. That's the reason that you can access its keys (for example payload.after). On the other hand if the input is a string containing a valid supported format (JSON, XML, etc) then you can use read(). – aled Aug 29 '22 at 14:43