简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM