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

DataWeave中Pluck函数使用问题求助:无法实现目标JSON转换

问题描述

我尝试用DataWeave的Pluck函数实现以下JSON转换,但没成功,请求帮助:

输入JSON

{
"EmpoyeeID" : "123" ,
"employee_salary_in_last3_months" :  1000 ,
"employee_salary_in_last6_months": 1750,
"employee_salary_in_last12months" : 3000
}

期望输出JSON

{
"EmpoyeeID": "123",
"Salary": {
    "Amounts": [
        {
            "Duration": "3 months",
            "Salary": "1000"
        },
        {
            "Duration": "6 months",
            "Salary": "1750"
        },
        {
            "Duration": "12 months",
            "Salary": "3000"
        }
    ]
}
}

我尝试的DataWeave代码

%dw 2.0
output application/json
---
{
"EmpoyeeID" : payload.EmpoyeeID,
"Salary": {
      "Amounts": payload pluck ((value, key, index) -> 
      
      "Duration" : value.employee_salary_in_last3_months
      
      )
}
}

解决方案

你需要先过滤掉EmpoyeeID字段,只处理薪资相关的键值对,再从每个键名中提取月份信息,同时正确映射薪资值。正确的DataWeave代码如下:

%dw 2.0
output application/json
---
{
    "EmpoyeeID": payload.EmpoyeeID,
    "Salary": {
        "Amounts": payload 
            // 过滤出薪资相关字段,排除EmpoyeeID
            filterObject ((value, key) -> key startsWith "employee_salary_in_last")
            // 遍历处理每个薪资字段
            pluck ((salaryValue, salaryKey) -> {
                // 从键名提取月份并格式化
                "Duration": (salaryKey splitBy "last")[1] replace "months" with "" ++ " months",
                // 将薪资值转为字符串(无需转字符串可去掉toString())
                "Salary": salaryValue toString()
            })
    }
}

代码说明

  1. filterObject:筛选出所有以employee_salary_in_last开头的字段,排除无关的EmpoyeeID,避免无效遍历。
  2. pluck遍历逻辑:
    • 通过splitBy("last")拆分薪资字段名,提取出月份部分并调整为"X months"的格式。
    • 直接使用当前遍历的salaryValue作为薪资值,按需转为字符串类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:42:40