-1

I need to translate the given payload to 6 different language (I used translator API), I only translated one language using the code below:

%dw 2.0
output application/json
---
{
    "text": [payload],
    "source": "en",
    "target": "et"
}

INPUT PAYLOAD:

"A quitter never wins and a winner never quits"

OUTPUT:

{
  "translations": [
    {
      "translation": "Kui sul on unistused, siis on sinu kohustus need teoks teha."
    }
 ],
  "word_count": 13,
  "character_count": 65
}
aled
  • 21,330
  • 3
  • 27
  • 34
  • 1
    Where the inputs for the "translations" attribute are coming from? The script that you shared seems to generate the input for calling a 'translator API'. It is not clear exactly what you are asking for, and why you made the question about using a for loop, that DataWeave doesn't has. Calling an API is not something you do inside DataWeave. Kindly read https://stackoverflow.com/help/how-to-ask for tips on how to improve your question. – aled Dec 28 '21 at 12:12

1 Answers1

1

DataWeave is a functional language specialized for transforming data. It does not has a "for loop" structure. It does has a map() function that can be used to transform arrays. I understand that you want to execute the same API request for different languages. For that you should use the Foreach scope for flows in Mule. You can combine both, using map() to create an array of requests for each language, and the Foreach scope to iterate over the list of requests inputs and execute the actual request.

Example with languages selected at random:

<set-payload value="A quitter never wins and a winner never quits"/>
<set-variable variableName="languages" value="#[ ['en', 'et', 'ru', 'nl', 'pl', 'it'] ]"/>
<ee:transform doc:name="Transform Message">
    <ee:message >
        <ee:set-payload ><![CDATA[%dw 2.0
            output application/java
            ---
            vars.languages map 
                { "text": [payload], "source": "en", "target": $ }  
        ]]>
        </ee:set-payload>
    </ee:message>
</ee:transform>
<foreach doc:name="For Each">
    <logger message="sending request to translate: #[payload]"/>
    <!-- call the translation API -->
</foreach>

The logger output will be:

sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=en}
sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=et}
sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=ru}
sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=nl}
sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=pl}
sending request to translate: {text=[A quitter never wins and a winner never quits], source=en, target=it}
aled
  • 21,330
  • 3
  • 27
  • 34