gtx911
gtx911

Reputation: 1289

Mule Dataweave 2 - List of JSON Strings to Array Object

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.

Upvotes: 1

Views: 4141

Answers (2)

machaval
machaval

Reputation: 5059

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.

Upvotes: 5

AnupamBhusari
AnupamBhusari

Reputation: 2415

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.

Upvotes: 0

Related Questions