根据MuleSoft DataWeave 2.0中的输入参数创建一个JSON对象



所以我有一个REST API,它可以有输入参数:START、STOP、RESTART。Start和Stop是REST API的不同操作,但RESTART本质上意味着Stop和Start。因此,我想根据选择的操作创建一个1个节点或2个节点的动态JSON。例如,对于START/STOP,JSON将是:

{ "appID": "1234",
"operation": "START"}

{ "appID": "1234",
"operation": "STOP"}

而对于RESTART来说,它就像:

{ "appID": "1234","operation": "STOP"},{ "appID": "1234","operation": "START"}

然后我可以循环通过这个数组并调用我的API一两次。然而,我无法理解如何根据作为输入传递给RESTneneneba API调用的Operation-param在数据编织中动态创建此JSON。我曾尝试创建一个具有2个节点JSON节点的变量,然后尝试too循环,但这似乎不起作用。

我试过这样的东西:

var count = 0
var appID = "1234567890"
var op = "START"
---
(operation map ((item, index) -> {
"appID": appID,
"operation": if(op=='START' and index == 0) "START"
else if(op=='STOP' and index==0) "STOP" 
else if(op=='RESTART' and index==0) "STOP" 
else if(op=='RESTART' and index==1) "START" 
else ''
})) [ 0 to operation.totalcount - count ]

其中Count的值基于操作为0或1

如果我正确理解输入值operation是否为";重启";则脚本应该返回元素start和stop的数组;START";只是一个起始元素;"停止";只是一个停止元件。我假设输出总是一个数组。

对于这个脚本,变量op表示输入。我使用op的值来返回操作,如果它不是"0";重新启动";。如果是,我返回";"停止";第一个元素,并添加第二个元素用于";START";。

%dw 2.0
output application/json
var appID = "1234567890"
var op = "RESTART"
---
[
{
"appID": appID,
"operation": if(op !='RESTART') op
else "STOP" 
}
] ++ if (op =='RESTART') [{
"appID": appID,
"operation": "START" 
}] else []

输出:

[
{
"appID": "1234567890",
"operation": "STOP"
},
{
"appID": "1234567890",
"operation": "START"
}
]

最新更新