1

I get from an external API a text/plain body with the following content. The output has the same format, JSON per line.

{"update":"7.6"}
{"update":"3.2"}
{"update":"1.3"}

The output expected (Object Array):

[{"version":"7.6"},{"version":"3.2"},{"version":"1.3"}]

How can I loop each String line and transform to Array of Objects?

Assuming I have to transform each line to JSON first.

2 Answers 2

5

Hi your input payload is a json lines kind. There is a simple way to support this.

%dw 2.0
output application/json
---
payload splitBy  "\n" map ((jsonValue, index) -> read(jsonValue, "application/json"))

This will split your input by lines and read each line.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use lookup function from dataweave for converting each line to JSON. Pass JSONstring as input to lookup function and return Json object. Following code should works fine

Main dataweave which takes text/plain as input but consider it as single column CSV without any header.

<dw:transform-message doc:name="Transform Message">
    <dw:input-payload mimeType="application/csv">
        <dw:reader-property name="header" value="false"/>
        <dw:reader-property name="separator" value="|"/>
    </dw:input-payload>
    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload map lookup('getJsonData',$.column_0)]]>
    </dw:set-payload>
</dw:transform-message>

Above script calls following lookup function which takes input as JSON string nd output as JSSON object.

    <flow name="getJsonData">
        <dw:transform-message doc:name="Transform Message">
            <dw:input-payload mimeType="application/json"/>
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
        </dw:transform-message>
    </flow>  

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.