Pierre
Pierre

Reputation: 61

Mule 4 Dataweave: Array from script output to JSON

After a script module execution, I get the output below:

[
"0": [
"0": ["A","B","C"],
"1": ["D","E","F"]
],
"1": [
"0": ["A","B","C"],
"1": ["D","E","F"],
"2": ["G","H","I"]
],
"2": [
"0": ["A","B","C"],
"1": ["D","E","F"],
"2": ["G","H","I"]
]
]

And I would like to get only the values, not the keys. So the expected output would be:

[
   [
      ["A","B","C"],
      ["D","E","F"]
   ],
   [
      ["A","B","C"],
      ["D","E","F"],
      ["G","H","I"]
   ],
   [
      ["A","B","C"],
      ["D","E","F"],
      ["G","H","I"]
   ]
]

I tried to use the map function and the valuesOf function, but without any luck.

Thanks!

Upvotes: 0

Views: 303

Answers (2)

santa
santa

Reputation: 76

Another option supposing the output looks like this

[
  {
    "0": {
      "0": ["A","B","C"],
      "1": ["D","E","F"]
    }
  },
  {
    "1": {
      "0": ["A","B","C"],
      "1": ["D","E","F"],
      "2": ["G","H","I"]
    }
  },
  {
    "2": {
      "0": ["A","B","C"],
      "1": ["D","E","F"],
      "2": ["G","H","I"]
    }
  }
]

this script turns it into your desired output

payload map (valuesOf($) flatMap valuesOf($))

output

[
  [
    ["A","B","C"],
    ["D","E","F"]
  ],
  [
    ["A","B","C"],
    ["D","E","F"],
    ["G","H","I"]
  ],
  [
    ["A","B","C"],
    ["D","E","F"],
    ["G","H","I"]
  ]
]

Upvotes: 1

aled
aled

Reputation: 25699

Assuming the input and the first childs are really objects, you can use pluck() at the top level to extract as an array of objects, then map each of the childs to use pluck() again.

Input:

{
    "0": {
        "0": ["A","B","C"],
        "1": ["D","E","F"]
    },
    "1": {
        "0": ["A","B","C"],
        "1": ["D","E","F"],
        "2": ["G","H","I"]
    },
    "2": {
        "0": ["A","B","C"],
        "1": ["D","E","F"],
        "2": ["G","H","I"]
    }
}

Script:

%dw 2.0
output application/json  
---
payload 
    pluck $ 
    flatMap 
        ($ pluck ((value, key, index) -> value))

Output:

[
  [
    [
      "A",
      "B",
      "C"
    ],
    [
      "D",
      "E",
      "F"
    ]
  ],
  [
    [
      "A",
      "B",
      "C"
    ],
    [
      "D",
      "E",
      "F"
    ],
    [
      "G",
      "H",
      "I"
    ]
  ],
  [
    [
      "A",
      "B",
      "C"
    ],
    [
      "D",
      "E",
      "F"
    ],
    [
      "G",
      "H",
      "I"
    ]
  ]
]

Upvotes: 0

Related Questions