我想从json数组对象中检索键值对。我正在尝试使用输入构建动态的where子句。如果键值在数组中相同,那么我想将其与“ IN”运算符一起使用,否则我想使用“ AND”。使用两个示例解释这两种情况
输入1:
"values": [
{
"id": "123"
},
{
"id": "455"
}
]
预期输出:
**"Where id in ('123','455')"**
Input2:
"values": [
{
"id": "123"
},
{
"name": "abc"
}
]
预期输出:
**"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 ")