maco
maco

Reputation: 65

How to access a JSON inside an XML in dataweave?

I've got a xml file containing order data and order line items. Additionally there is information for some of the line items stored in a JSON string inside the XML, and I'm struggling to access these information properly.

Source looks like this:

<orders>
    <order order-no="00006640">
        <currency>EUR</currency>
        <product-lineitems>
            <product-lineitem>
                <position>1</position>
                <net-price>22.37</net-price>
            </product-lineitem>
            <product-lineitem>
                <position>2</position>
                <net-price>10.99</net-price>
            </product-lineitem>
        </product-lineitems>
        <custom-attribute attribute-id="return">
            <value>{"status":"RETURNED","position":"2","quantity":"1.000"}</value>
        </custom-attribute>
    </order>
</orders>

Target should look like this (moved the quantity from the JSON to the corresponding line item):

<orders>
    <order order-no="00006640">
        <currency>EUR</currency>
        <product-lineitems>
            <product-lineitem>
                <position>1</position>
                <net-price>22.37</net-price>
            </product-lineitem>
            <product-lineitem>
                <position>2</position>
                <net-price>10.99</net-price>
                <quantity>1</quantity>
            </product-lineitem>
        </product-lineitems>
    </order>
</orders>

Is there a way to solve this in one dataweave transformation?

Upvotes: 0

Views: 358

Answers (1)

Salim Khan
Salim Khan

Reputation: 4303

Something like this maybe..

%dw 2.0
output application/xml
var extractedJson = read(payload.orders.order."custom-attribute".value,"application/json")
var updProdLineItems = "product-lineitems": payload.orders.order.."product-lineitems" map {
                     "product-lineitem": $.*"product-lineitem" map{
                                     a: $ ++ (if($.position == extractedJson.position) ({"quantity": extractedJson.quantity}) else {})
                     }.a 
             }
---
{
orders:
 payload.orders mapObject {
     order @("order-no" : $.@"order-no"): $ - "custom-attribute" - "product-lineitems" ++ updProdLineItems

 }
}

Upvotes: 1

Related Questions