【问题标题】:Convert JSON with a Parent ID and child array into an array of one json object per element in child array in Dataweave将带有父 ID 和子数组的 JSON 转换为 Dataweave 中子数组中每个元素一个 json 对象的数组
【发布时间】:2019-07-25 03:58:40
【问题描述】:

我需要将一个包含子数组的对象的 json 数组转换为一个对象数组,每个子数组对象都有一个记录(对象)。

输入:

[
  {
    "recId": 1,
    "Attrs": [
      {
        "color": "red",
        "priority": 1
      },
      {
        "color": "purple",
        "priority": 2
      }
    ]
  },
  {
    "recId": 2,
    "Attrs": [
      {
        "color": "gold",
        "priority": 3
      },
      {
        "color": "blue",
        "priority": 2
      }
    ]
  },
  {
    "recId": 3,
    "Attrs": null
  }
]

期望的输出:

[
  {
    "recId": 1,
    "color": "red",
    "priority": 1
  },
  {
    "recId": 1,
    "color": "purple",
    "priority": 2
  },
  {
    "recId": 2,
    "color": "gold",
    "priority": 3
  },
  {
    "recId": 2,
    "color": "blue",
    "priority": 2
  }
]

我尝试了几种不同的方法,但均未成功。我在任何地方或文档中都找不到任何好的示例。我无法弄清楚如何捕获 recId 并使 Attrs 的每个对象成为单独的记录。

【问题讨论】:

    标签: dataweave


    【解决方案1】:

    您可以使用 ma​​p 转换/迭代数组上的每个项目。然后使用另一个地图获取 Attrs 中的每个对象,并返回相同的对象加上 recId

    这将输出一个数组数组,因此您需要将其展平(使用函数 flatten 或使用 flatMap 而不是第一个地图)。

    要忽略 null,您可以使用 writer 属性 skipNullOn

    %dw 2.0
    output application/json skipNullOn="everywhere"
    ---
    flatten(payload map ((item, index) -> 
        item.Attrs map ((attr, index) -> 
            {"recId": item.recId} ++ attr
            )
        )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-29
      • 2016-05-27
      • 2022-01-09
      • 2019-09-08
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多