Search code examples
muledataweavemulesoftmule-component

URL encoding in DataWeave


I need to hit a service which needs URL encoding in the query parameters and I have the input as below:

{
"test" : ["123", "124"]
}

which when I encode using https://www.urlencoder.io/ I get the below format:

%7B%0A%09%22test%22%20%3A%20%5B%22123%22%2C%20%22124%22%5D%0A%09%7D

and the above I need to pass in the query parameters.

I try to generate the above URL encoder output in mulesoft with the below dataweave:

%dw 2.0
output application/x-www-form-urlencoded
---
payload

but it gives me the below output, which is not what I want:

test=123&test=124

So please let me know how I can generate the below pattern in mule for the above input:

%7B%0A%09%22test%22%20%3A%20%5B%22123%22%2C%20%22124%22%5D%0A%09%7D

Solution

  • You are mixing two very different concepts.

    application/x-www-form-urlencoded is a MIME Type that is typically used to POST a web form data over HTTP. I mentioned a web form, but technically it can be used send any "JSON like" data and when you do that, it becomes key=value pairs separated by & when there are multiple fields.
    For Example {"field1": "value1", "field2": "value2"} will become field1=value1&field2=value2 when represented as x-www-form-urlencoded

    On the other hand, URL Encoding is used to "Percentage Encode" certain characters that are not allowed in URLs (like non ASCII characters) or that have special meaning for URLs (like ?, &) so that you can safely use it to construct a URL.

    What you need is the encodeURIComponent function that you can use to encode your String. Also, URL encoding is for Strings not for JSON Objects. So you will need to write the JSON payload as String. Something like below

    %dw 2.0
    import encodeURIComponent from dw::core::URL
    output application/java
    ---
    encodeURIComponent(
        write(payload, "application/json")
    )
    

    Keep in mind you will get different results depending on if you want to keep the indentation or not while writing the payload to String. For example this will give you a different (and much shorter) result then the one above.

    %dw 2.0
    import encodeURIComponent from dw::core::URL
    output application/java
    ---
    encodeURIComponent(
        write(payload, "application/json", {indent: false}) // Shorter URL as it will not keep indentation
    )
    

    It is highly preferred not to keep indentations, if you are using this to generate a URL, as it will keep the URLs significantly shorter.