0
votes

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"
            }]
          }
    }
}
1
Is it a single level nested object ? MyValues that is . Can you paste a bit more in the sample input ? - Salim Khan
No it can be multiple like sometime it shows one record sometimes it shows 3 4 or more than that, so if it is more then one then the [] sign is coming but i need to make both response consistent. - sivoc98608
For more than one it is coming "MyValues":[{ "Name":"ABC TEST", "Phone":"1234" }, { "Name":"ABC TEST2", "Phone":"12345" }] the above is perfectly fine. Now i want for even one record it should be in array as to make both consistent. @SalimKhan - sivoc98608

1 Answers

1
votes

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")