1

I want to transform the below input into the given output. My requirement is to convert the key/value pairs into the Objects having key and value as individual elements in an object.

Input:

 {
    "data": [
        {
            "Amount": 20,
            "CostPrice": 50,
            "SellingPrice": 100,
            "FinalPrice": 120,
            "Quantity": 2,
            "Tax": 21.6
        }
    ]
}

Output:

{
"data": [
    {
        "key": "Amount",
        "value": "20"
    },
    {
        "key": "CostPrice",
        "value": "50"
    },
    {
        "key": "SellingPrice",
        "value": "100"
    },
    {
        "key": "FinalPrice",
        "value": "120"
    },
    {
        "key": "Quantity",
        "value": "2"
    },
    {
        "key": "Tax",
        "value": "21.6"
    }
]

}

machaval
  • 4,969
  • 14
  • 20

1 Answers1

1

Use the pluck() function to transform each key-value pair into an item in an array.

%dw 2.0
output application/json
---
data: payload.data[0] pluck 
    {
        key: $$,
        value: $
    }

Output:

{
  "data": [
    {
      "key": "Amount",
      "value": 20
    },
    {
      "key": "CostPrice",
      "value": 50
    },
    {
      "key": "SellingPrice",
      "value": 100
    },
    {
      "key": "FinalPrice",
      "value": 120
    },
    {
      "key": "Quantity",
      "value": 2
    },
    {
      "key": "Tax",
      "value": 21.6
    }
  ]
}
aled
  • 21,330
  • 3
  • 27
  • 34