sivoc98608
sivoc98608

Reputation: 1

Mule 3 convert a json object in to an array

I have the below dynamic response coming from third party API, now I need to transform only the particular JSON object ("MyValues") into an array.

The payload here is sample is is very large .

Current Output:

{
    "Body": {
          "Status": "200",
          "Result": {
            "MyValues":{
                "Name":"ABC TEST",
                "Phone":"1234"
            }
          }
    }
}

Expected Output:

{
    "Body": {
          "Status": "200",
          "Result": {
            "MyValues":[{
                "Name":"ABC TEST",
                "Phone":"1234"
            }]
          }
    }
}

Upvotes: 0

Views: 885

Answers (1)

aled
aled

Reputation: 25812

You can use pattern matching based on the type received, array or object. I created a recursive function to find the instances of a key name and perform the change in a generic way.

Example:

%dw 1.0
%output application/json
%function convertToSingleArray(x, key)
    x match {
                  // OPTIONAL :array  ->  x map convertToSingleArray($, key),
                  :object ->  x mapObject {($$): [$] when ( (($$ as :string) == key) and ((typeOf $) as :string  == ":object")) otherwise convertToSingleArray($, key)
                  },
                  default  ->  x
            }
---
convertToSingleArray(payload, "MyValues")

Upvotes: 1

Related Questions