You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mule 4 DataWeave:JSON数组按Group映射属性值的实现方法

在Mule 4 DataWeave中实现JSON数组的指定属性映射需求

需求说明

需要从输入的JSON数组对象中,根据指定的group值(如color/size/category),映射到对应desc值,生成符合要求的输出:

  • systemAttributeName需为首字母大写的group值拼接"description",不能与原group同名
  • 仅当存在对应group时,才生成该属性
  • 输出需按照每个systemDetails元素拆分,每个元素对应一个独立的JSON对象
  • desc值中的空格需去除(如28 inch转为28inch)

输入JSON

{
  "system": "Computer",
  "description": "",
  "details": "",
  "systemDetails": [
    {
      "systemnumber": "A123",
      "description": [
        {
          "group": "color",
          "desc": "yellow"
        },
         {
          "group": "variant",
          "desc": "20k model"
        },
        {
          "group": "category",
          "desc": "Desktop"
        }
      ]
    },
    {
      "systemnumber": "B123",
      "description": [
        {
          "group": "size",
          "desc": "28 inch"
        },
        {
          "group": "category",
          "desc": "Laptop"
        }
      ]
    }
  ]
}

期望输出

{
  "systemId": "A123",
  "systemLevelDetails": [
    {
      "systemAttributeName": "Colordescription", 
      "values": "yellow"
    },
    {
      "systemAttributeName": "Categorydescription",
      "values": "Desktop"
    }
  ]
}

{
  "systemId": "B123",
  "systemLevelDetails": [
    {
      "systemAttributeName": "Sizedescription",
      "values": "28inch"
    },
    {
      "systemAttributeName": "Categorydescription",
      "values": "Laptop"
    }
  ]
}

DataWeave实现代码

%dw 2.0
output application/json
// 定义需要处理的目标group列表,排除不需要的类型
var targetGroups = ["color", "size", "category"]
---
payload.systemDetails map (item) -> {
    systemId: item.systemnumber,
    systemLevelDetails: item.description 
        // 筛选出属于目标group的元素
        filter (descItem) -> targetGroups contains descItem.group
        map (descItem) -> {
            // 生成首字母大写的systemAttributeName
            systemAttributeName: (upper(descItem.group[0]) ++ descItem.group[1 to -1]) ++ "description",
            // 去除desc中的空格
            values: descItem.desc replace " " with ""
        }
}

代码说明

  1. 目标group过滤:通过targetGroups变量明确需要处理的group类型,用filter方法自动排除不需要的元素(如示例中的variant)
  2. 属性名生成:通过字符串操作将group值首字母大写,再拼接"description",确保与原group名称不同
  3. 内容格式化:用replace方法去除desc值中的空格,匹配输出要求
  4. 批量转换:通过map方法遍历每个systemDetails元素,生成独立的输出对象

内容的提问来源于stack exchange,提问作者MyDream

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 06:23:12