0
votes

I have the following requirement need to interate the dynamic json key need to use this json key and iterate through it This is my input

[  
  {  
    "eventType":"ORDER_SHIPPED",
    "entityId":"d0594c02-fb0e-47e1-a61e-1139dc185657",
    "userName":"[email protected]",
    "dateTime":"2010-11-11T07:00:00Z",
    "status":"SHIPPED",
    "additionalData":{  
      "quoteId":"d0594c02-fb0e-47e1-a61e-1139dc185657",
      "clientReferenceId":"Srites004",
      "modifiedDt":"2010-11-11T07:00:00Z",
      "packageId":"AIM_PACKAGE",
      "sbsOrderId":"TEST-TS-201809-79486",
      "orderReferenceId":"b0123c02-fb0e-47e1-a61e-1139dc185987",
      "shipDate_1":"2010-11-11T07:00:00Z",
      "shipDate_2":"2010-11-12T07:00:00Z",
      "shipDate_3":"2010-11-13T07:00:00Z",
      "shipMethod_1":"UPS Ground",
      "shipMethod_3":"UPS Ground3",
      "shipMethod_2":"UPS Ground2",
      "trackingNumber_3":"333",
      "trackingNumber_1":"2222",
      "trackingNumber_2":"221"
    }
  }
]

I need output like following

{  
  "trackingInfo":[  
    {  
      "shipDate":"2010-11-11T07:00:00Z",
      "shipMethod":"UPS Ground",
      "trackingNbr":"2222"
    },
    {  
      "shipDate":"2010-11-12T07:00:00Z",
      "shipMethod":"UPS Ground2",
      "trackingNbr":"221"
    },
    {  
      "shipDate":"2010-11-13T07:00:00Z",
      "shipMethod":"UPS Ground3",
      "trackingNbr":"333"
    }
  ]
}

the shipdate, shipmethod ,trackingnumber can be n numbers. how to iterate using json key.

1

1 Answers

2
votes

First map the array to iterate and then use pluck to get a list of keys.

Then as long as there is always the same amount of shipDate to shipMethod etc fields. filter the list of keys to only iterate the amount of times those field combinations exist.

Then construct the output of each object by dynamically looking up the key using 'shipDate__ concatenated with the index(incremented by 1 because your example starts at 1 and dw arrays start at 0):

%dw 2.0
output application/json

---

    payload map ((item, index) -> item.additionalData pluck($$) filter ($ contains 'shipDate')  map ((item2, index2) ->
        using(incIndex=(index2+1 as String)){ 
            "shipDate": item.additionalData[('shipDate_'++ incIndex)],
            "shipMethod": item.additionalData[('shipMethod_'++ incIndex)],
             "trackingNbr": item.additionalData[('trackingNumber_'++ incIndex)],
        }
    )

)

In DW 1.0 syntax:

%dw 1.0
%output application/json  
---
payload map ((item, index) -> item.additionalData pluck ($$) filter ($ contains 'shipDate') map ((item2, index2) -> 
    using (incIndex = (index2 + 1 as :string))
      {
        "shipDate": item.additionalData[('shipDate_' ++ incIndex)],
        "shipMethod": item.additionalData[('shipMethod_' ++ incIndex)],
        "trackingNbr": item.additionalData[('trackingNumber_' ++ incIndex)]
      }))

It's mostly the same, except:

  • output => %output
  • String => :string