1

I need to format an incoming payload JSON to a certain manner. The sample payload JSON is given below.

[
  {
    "value": {
      "States": [
        {
          "Name": "New South Wales",
          "Code": "NSW"
        }
      ]
    }
  },
  {
    "value": {
      "States": [
        {
          "Name": "Western Australia",
          "Code": "WA"
        }
      ]
    }
  }
]

The output that I'm trying to get to is given below:

[
  {
    "SystemCode": "STATE",
    "Name": "StateName",
    "Code": "NSW"
  },
  {
    "SystemCode": "STATE",
    "Name": "StateName",
    "Code": "WA"
  }
]

As you can see above, in the output, SystemCode and Name will remain constant, whereas the Code value will change as per the incoming payload. Once the required output is generated, I need to store the same as a JSON in a session variable. How can I achieve this in Mule dataweave 1.0 Please note that I can receive multiple arrays as payload with different codes. Thanks in advance.

Triumph Spitfire
  • 663
  • 15
  • 38

2 Answers2

6

Try this:

%dw 1.0
%output application/json

%var codes = payload..Code

%var baseObj = {
    "SystemCode" : "STATE",
    "Name"       : "StateName"
}
---
codes map (baseObj ++ {"Code": $})

To set it to a session var:

<dw:transform-message>
  <dw:set-session-variable variableName="sessionVarName">
    <![CDATA[
      <YOUR CODE HERE>
    ]]>
  </dw:set-session-variable>
</dw:transform-message>
jerney
  • 2,187
  • 1
  • 19
  • 31
  • Thanks a lot for your response. I get this error while executing. Type mismatch for 'flatten' operator found :null required :array – Triumph Spitfire Aug 26 '19 at 18:31
  • Could you also let me know how the flatten works for the below array: "Codes": [ { "CodeValue": "TRA" }, { "CodeValue": "MED" } – Triumph Spitfire Aug 26 '19 at 18:33
  • Actually you shouldn't even need flatten. Try my edited version, it uses the descendants selector: https://docs.mulesoft.com/mule-runtime/3.9/dataweave-selectors#descendants-selector – jerney Aug 26 '19 at 18:51
0

Try this :

%dw 1.0
%output application/json
---
payload.value.States map 
{
    "SystemCode": "STATE",
    "Name": "StateName",
    "Code": $.Code[0]
}
Viktor
  • 2,623
  • 3
  • 19
  • 28
AshMule
  • 21
  • 2