1

I am defining the global function for payload but in the dataweave 1.0 I am not able to do the task. I have to define a separate global dataweave file where I have to add the conditions for payload like if gender== "male" then title= "mr." How can I perform the task. I have added my input and expected payload.

input payload:

{
    "persons": [
        {
            "name": "Devendra",
            "gender": "male",
            "age": 25
        },
        {
            "name": "aman",
            "gender": "male",
            "age": 16
        }
    ]
}

expected payload:

{
    "persons": [
        {
            "title": "MR.",
            "name": "Devendra",
            "gender": "male",
            "age": 25,
            "adult": true
        },
        {
            "title": "MS.",
            "name": "Seema",
            "gender": "female",
            "age": 16,
            "adult": false
        }
    ]
}
4

1 回答 1

2

在 Dataweave 1 中,您可以通过在 src/main/resources 中创建一个 dwl 文件来定义一个全局库,如下所示:

src/main/resources/dw/myFunctions.dwl:

%dw 1.0
%function titleForGender(gender)("mr" when gender=="male" otherwise "whoKnows?")
---
{
"titleForGender": titleForGender
}

此脚本创建一个全局函数,然后将其公开在主体中,以便其他脚本可以使用它。

然后在你的主要 dw 转换中是这样的:

%dw 1.0
%output application/json

%var sampleData={persons:[{name:"Devendra", gender:"male",age:25}, {name:"aman", gender:"male",age:16}]}
%var lib = readUrl("classpath://dw/myfunctions.dwl")
 ---
persons: sampleData.persons map {
    "person": $ ++ {title: lib.titleForGender($.gender)}
}

它用于readUrl从全局文件中以 var 的形式读入函数lib,然后在映射人员数据时使用它,将 传递gender给函数并获取函数返回的标题。

这输出:

{
  "persons": [
    {
      "person": {
        "name": "Devendra",
        "gender": "male",
        "age": 25,
        "title": "mr"
      }
    },
    {
      "person": {
        "name": "aman",
        "gender": "male",
        "age": 16,
        "title": "mr"
      }
    }
  ]
}
于 2019-05-23T16:28:41.370 回答