Dataweave:将单个项目放入数组中,如果不为null

时间:2016-06-10 16:05:20

标签: mule dataweave

我从API调用接收有效负载,我需要将单个值转换为具有单个元素的数组。

说这两个例子是我的有效载荷:

{
  "name": "Bob",
  "loanTerms": {
    "term": 120,
    "loanRate": 0.0213,
    "maxApproved": 60000
  }
}

{
  "name": "Bob",
  "loanTerms": null
}

我想做这样的事情:

{
    Name: payload.name
    LoanOptions: [
        {
            ProductName: payload.loanTerms.term as :string,
            DisplayName: null,
            LoanTermMonth: payload.loanTerms.term,
            Rate: payload.loanTerms.loanRate*100,
            Amount: payload.loanTerms.maxApproved
        } when payload.loanTerms?
    ]
}

但是编辑一直在向我说'#34;这条线的多个标记" (LoanOptions:行)

3 个答案:

答案 0 :(得分:3)

when 声明不完整。一方面,缺少 otherwise 运算符。另一方面,在 payload.loanTerms? 之后还有其他内容。此外,Name字段后需要逗号。

另外,您可以移除方括号:

{
    Name: payload.name,
    LoanOptions:
        [{
            ProductName: payload.loanTerms.term as :string,
            DisplayName: null,
            LoanTermMonth: payload.loanTerms.term,
            Rate: payload.loanTerms.loanRate*100,
            Amount: payload.loanTerms.maxApproved
        }] when payload.loanTerms != null
        otherwise []       
}

答案 1 :(得分:0)

这可能不是一个优雅的解决方案,但可以为您完成工作。

%dw 1.0
%output application/json
---
{
 Name: payload.name,
 (LoanOptions:          
       [{
        ProductName: "abc" as :string,
        DisplayName: null,
        LoanTermMonth: payload.loanTerms.term,
        Rate: payload.loanTerms.loanRate*100,
        Amount: payload.loanTerms.maxApproved

        }]) when payload.loanTerms != null,
 (LoanOptions: null) when payload.loanTerms == null

 }

如果您不希望在输入中没有loanTerms时显示任何内容,则可以删除解决方案中提到的第二个Loanoptions(如下所示)。

%dw 1.0
%output application/json
---
{
 Name: payload.name,
 (LoanOptions:          
   [{
    ProductName: "abc" as :string,
    DisplayName: null,
    LoanTermMonth: payload.loanTerms.term,
    Rate: payload.loanTerms.loanRate*100,
    Amount: payload.loanTerms.maxApproved

    }]) when payload.loanTerms != null
 }

答案 2 :(得分:0)

您需要在标记时添加条件以及添加其他条件。看一下下面的代码片段

%dw 1.0

%output application/json

{ Name: payload.name, LoanOptions: { ProductName: payload.loanTerms.term as :string, DisplayName: null, LoanTermMonth: payload.loanTerms.term, Rate: payload.loanTerms.loanRate*100, Amount: payload.loanTerms.maxApproved } when (payload.loanTerms != null) and (payload.loanTerms != []) and (payload.loanTerms != "") otherwise null

    }

}