0
votes

struggling a bit to do that I want, perhaps you may help me. I have a dynamic output object with different amount of items and I don't know name of keys, so I just do output like this:

%dw 1.0
%Output application/json skipNullOn = "everywhere"
---
flowVars.OutputListArr orderBy $$

this work fine for payload like:

ccc="333", bbb="222", aaa="111", ddd="444"

but now I have situation then one of keys is a list, but I want to return it as array, e.g.

bbb = "221,222,223"

I can do it by

splitBy "," ->> "['221', '222', '223']"

but don't know how to do it together. So then input will be like that:

{ccc="333",bbb="221,222,223",aaa="111", ddd="441, 442, 443"}

I want to transform it into that:

"aaa": "111",
"bbb": ["221","222","223"],
"ccc": "333"
"ddd": "441, 442, 443",

so only bbb string get splitted (I know bbb key name)

upd: just get a situation then bbb may have only one member, so expecting a way to check key attribute name and then make it array ish... so dont belong on content it self

1

1 Answers

1
votes

You can use a recursive function that checks the type of the value and applies the right method to each one. Additionally it recurses on objects, in case there is a nested object.

Example:

%dw 1.0
%output application/json

%function filterKeys(o, k)
    o mapObject
            { 
                ($$): 
                    $ when ($ is :string and (k contains ($$ as :string)))
                    otherwise orderMembers($, k)
            } 
            orderBy $$

%function splitString(s) s splitBy "," map trim $

%function orderMembers(x, k)
    x match {
        a is :array -> a orderBy $,
        o is :object -> filterKeys(o, k),
        s is :string -> orderMembers(splitString(s), k)
             when s  contains ',' otherwise s,
        default -> $
    }
    
%var testData={ccc:"333", ddd: ["555", "333", "222"], bbb: "223,221,222", eee: "456, 789, 123", aaa: 11}
---
orderMembers(testData, ["bbb"]) 

Output:

{
  "aaa": 11,
  "bbb": "223,221,222",
  "ccc": "333",
  "ddd": [
    "222",
    "333",
    "555"
  ],
  "eee": [
    "123",
    "456",
    "789"
  ]
}

Update: added a key list of keys that we want to preserve, other keys that contain commas will be splitted. Note that I trimmed the splitted elements to avoid extra spaces. You can remove that if not needed.