如何根据 dataweave 中的键压缩 json 对象

And*_*ndy 0 mule anypoint-studio dataweave mule4 anypoint-platform

我有一个 json 结构如下:

[
  {
    "apiId": 18211158,
    "policyName0": "cors"
    
  },
  {
    "apiId": 18211158,
    "policyName1": "client-id-enforcement"
  },
  {
    "apiId": 18211150,
    "policyName0": "client-id-enforcement"
  },
  {
    "apiId": 18211162,
    "policyName0": "client-id-enforcement"
  },
  {
    "apiId": 18211162,
    "policyName1": "cors"
  },
  {
    "apiId": 18211162,
    "policyName2": "oauth"
  }
]
Run Code Online (Sandbox Code Playgroud)

我需要使用 dataweave 2.0 将其转换为以下内容

[
  {
    "apiId": 18211158
    "policyName0": "cors",
    "policyName1": "client-id-enforcement",
  },
  {
    "apiId": 18211150
    "policyName0": "client-id-enforcement",
  },
  {
    "apiId": 18211162
    "policyName0": "client-id-enforcement",
    "policyName1": "cors",
    "policyName2": "oAuth",

  }
]
Run Code Online (Sandbox Code Playgroud)

请注意,每个 apiID 可以有多个策略,并且会生成 policyName json 属性,并且 cal 的值范围为 1 到 9。

如何根据 apiID 压缩 json 作为 dataweave 中的键?

mac*_*val 5

最好的方法是使用 groupBy 来将组重塑为对象

%dw 2.0
output application/json
---
payload 
    groupBy ((value, key) -> value.apiId)
    pluck ((value, key, index) -> {
            "apiId": key,
            (value map ((item, index) -> item - "apiId"))
        })
Run Code Online (Sandbox Code Playgroud)