Json 从mule4中的数组对象获取键:值对
我想从json数组对象中检索键值对。我试图用输入构建一个动态where子句。如果数组中的键值相同,则我希望将其与“in”运算符一起使用,否则我希望使用“AND”。使用两个示例解释这两种场景 输入1:Json 从mule4中的数组对象获取键:值对,json,mule,dataweave,Json,Mule,Dataweave,我想从json数组对象中检索键值对。我试图用输入构建一个动态where子句。如果数组中的键值相同,则我希望将其与“in”运算符一起使用,否则我希望使用“AND”。使用两个示例解释这两种场景 输入1: "values": [ { "id": "123" }, { "id": "455" } ] 预期输出: **"Where id in ('123','455')"** **"Where id = '123' and name = 'abc'** 输入2: "values": [ {
"values": [
{
"id": "123"
},
{
"id": "455"
}
]
预期输出:
**"Where id in ('123','455')"**
**"Where id = '123' and name = 'abc'**
输入2:
"values": [
{
"id": "123"
},
{
"name": "abc"
}
]
预期输出:
**"Where id in ('123','455')"**
**"Where id = '123' and name = 'abc'**
提前感谢这会让你走上正确的道路
%dw 2.0
import * from dw::core::Arrays
output application/json
var values =
[
{
"id": "123"
},
{
"id": "abc"
}
]
---
if ( (values countBy ($.id != null)) > 1 )
"in"
else if ( (values countBy ($.id != null)) == 1 )
"and"
else
"idk"
检查所有按键是否相同,以区分不同的情况 您可以将joinBy函数与
“、”
或和“
一起使用来分隔这些值
%dw 2.0
import * from dw::core::Arrays
output application/json
var firstKey = keysOf(payload.values[0])[0]
var sameKeys = payload.values every ((item) -> keysOf(item)[0] == firstKey)
---
if (sameKeys)
"Where " ++ firstKey ++ " in ('" ++ (payload.values[firstKey] joinBy "','") ++ "')"
else
"Where " ++ (payload.values map ((item, index) -> keysOf(item)[0] ++ " = '" ++ valuesOf(item)[0] ++ "'") joinBy " and ")
Christian的方法,使用键集
%dw 2.0
import * from dw::core::Objects
import * from dw::core::Arrays
output application/json
var firstKey = keySet(payload.values[0])[0]
var sameKeys = payload.values every ((item) -> keySet(item)[0] == firstKey)
---
if (sameKeys)
"Where " ++ firstKey ++ " in ('" ++ (payload.values[firstKey] joinBy "','") ++ "')"
else
"Where " ++ (payload.values map ((item, index) -> keysOf(item)[0] ++ " = '" ++ valuesOf(item)[0] ++ "'") joinBy " and ")
我想,keysOf是在Dataweave2.3中引入的。我使用的是以前的版本。有什么建议可以取代它吗?我试过使用keySet,但即使这样似乎也不起作用。我已经更新了Christian使用keySet的方法,并将其作为答案发布在下面。嗯。。