Basic JSON formatting using Mule Expression Language

1.2k views Asked by At

When sending POST requests to an address on Slack, the JSON needs to be formatted as such:

{"channel": "#testing", "username": "test", "text": "Subject"}

Or something of the sort, which is normal. The problem I'm having is really basic, but basically, I need to send some details that are obtained from an email via JSON, something like this:

{"channel": "#testing", "username": "#[message.inboundProperties['From']]", "text": "Subject"}

And when I log the payload after this, I get:

{"channel": "#testing", "username": ""Doe, John" <[email protected]>", "text": "Subject"}

And this throws a 500 error code, presumably because it is no longer valid JSON (my guess would be because of the weird quotations, but then if I do something else and do something like this:

{"channel": "#testing", "username": "username", "text": "#[message.payload]"}

Gives me this:

{"channel": "#testing", "username": "username", "text": "email body
", "icon_emoji": ":man_with_turban:"}

Which looks valid to me, but does not work (perhaps there's a new line character or something, but even then it's just a character in a string is it not?)

I'm not sure how I could do this properly.

2

There are 2 answers

0
Gilberto Ibarra On

You can use this page to validate JSON:

https://www.jsoneditoronline.org/

{"channel": "#testing", "username": "username", "text": "email body", "icon_emoji": ":man_with_turban:"}
2
David Dossot On

The preferred approach for JSON generation in Mule is to create a datastructure (like a Map) and use the json:object-to-json-transformer to serialize it as JSON. This takes care of escaping.

If you persist in creating JSON as a string, you need to properly escape the values you inject (for example by using escapeJavaScript).