1
votes

I have the below requirement.

Input is

{ "packageConfiguration": [
      {
        "packageId": [
          "AIM_PACKAGE"
        ],
        "component": [
          "Handbook"
        ],
        "fieldName": [
          "Upload Handbook Document"
        ],
        "assetUrl": [
          "sflydamlocation.handbookfilename.pdf"
        ]
      }
    ]}

I need to convert above json array into this output format:

 {
        "pakage": ""packageId":"AIM_PACKAGE", "component":"Handbook",  "fieldName":"Upload Handbook Document","assetUrl":"sflydamlocation.handbookfilename.pdf""
}
2

2 Answers

1
votes

You can do that treating all fields as strings, however note that:

  1. The inner quotes must be escaped. Otherwise the output is not valid JSON.
  2. Take in account that the value of "package" is not really valid JSON either, in case you want to parse it. It should an object (eg " { \"package\":... }")
  3. This script expects all the arrays to have exactly 1 element. More elements are ignored and less could give an error. This is not a very robust design.

Script (not recommended):

%dw 2.0
output application/json

---
package: using (pc = payload.packageConfiguration[0]) (

        " \"packageId\": \"$(pc.packageId[0])\", " ++  
        " \"component\": \"$(pc.component[0])\" "  ++
        " \"fieldName\": \"$(pc.fieldName[0])\" "  ++
        " \"assetUrl\": \"$(pc.assetUrl[0])\" "
 )

Output:

{
  "package": " \"packageId\": \"AIM_PACKAGE\",  \"component\": \"Handbook\"  \"fieldName\": \"Upload Handbook Document\"  \"assetUrl\": \"sflydamlocation.handbookfilename.pdf\" "
}

This is an ugly string concatenation. Instead I would suggest to just write the desired output as a JSON object.

Script (recommended):

%dw 2.0
output application/dw
var pc = payload.packageConfiguration[0]
---
package: 
    write({
        packageId: pc.packageId[0],  
        component: pc.component[0],  
        fieldName: pc.fieldName[0],  
        assetUrl: pc.assetUrl[0]
        }, "application/json") replace /\n/ with ""

Output

{
  "package": "{  \"packageId\": \"AIM_PACKAGE\",  \"component\": \"Handbook\",  \"fieldName\": \"Upload Handbook Document\",  \"assetUrl\": \"sflydamlocation.handbookfilename.pdf\"}"
}

The second script is much cleaner, less error prone and returns an escaped JSON object that you could unescape to use as JSON.

0
votes

Something like this should work, unless you require something more flexible. I'm assuming you're working w/ Mule3/DW1:

%dw 1.0
%output application/json

%var packageConfig = payload.packageConfiguration[0]
---
{
  package: packageConfig mapObject ((value, key) -> {
    (key): value[0]
  })
}