问题描述
我正在将我的有效负载映射到一个新的有效负载,并在输出如下所示的位置添加一个 Errors 数组。 :
payload : [{
"test: "test","test2" : "","test3" : "test3"
},{
"test: "test","test2" : "test2","test3" : "test3"
}]
预期输出:`有效载荷:[{
"test: "test","test3" : "test3","Errors" : {
"test2" : "Test2 is NULL"
}
},"Errors" : {
}
}]`
预期输出:我想获得一个输出,其中我只从 Payload 获取所有对象,其中 Errors 数组具有任何非空值的键,否则应将其过滤掉。
我使用下面的表达式来实现,但这并不可行,因为它需要我为 Errors 数组中的每个键添加空检查。
errArr."Errors" filter ((item,index) -> item."test" != "" or item."test2" != "" or
item."test3" != "")
必须有更好的方法来做到这一点?有没有办法只检查每个项目(键)的值而不定义它们的名称?
解决方法
请注意,您的输入有一些错误。
脚本:
%dw 2.0
import * from dw::core::Arrays
import * from dw::core::Objects
output application/json
---
payload map {
($),Errors: $
filterObject ((value,key) -> isEmpty(value))
mapObject ((value,key) -> (key): key ++ " is NULL")
}
输入:
[
{
"test": "test","test2" : "","test3" : "test3"
},{
"test": "test","test2" : "test2","test3" : "test3"
}
]
输出:
[
{
"test": "test","test2": "","test3": "test3","Errors": {
"test2": "test2 is NULL"
}
},{
"test": "test","test2": "test2","Errors": {
}
}
]
,
试试这个,解释如下:
%dw 2.0
output application/json
var data = [{
"test": "test","test3" : "test3"
}
]
---
data map {
($),errors: $ mapObject (v,k) -> (
if (isEmpty(v)) {(k): "$(k) is empty"} else {}
)
}
这是算法以及文档中的链接:
- 使用
map
迭代数组中的对象 - 创建一个新对象并在新对象中添加现有的(键,值)对 使用 dynamic elements 功能。
- 将
errors
字段添加到新对象。使用mapObject
函数计算errors
对象,该函数标识所有空字段(注意我说的是空字段,而不仅仅是null
)。
我给您的建议是,确保您在提问时提供范围适当的输入和输出示例数据集。这将确保您能更及时地获得问题的答案。
,这就是你所追求的吗?
输入
[{
"test": "test","test3" : "test3","Errors" : {
"test": null,"test2" : "Test2 is NULL","test3" : ""
}
},{
"test": "1231test123","test2" : "123test23232","test3" : "12421test3","Errors" : {
"test": "",{
"test": "3asdsadasd","test2" : "123123","test3" : "d323e2d23","Errors" : {
"test": "123","test3" : ""
}
}
]
脚本
%dw 2.0
import * from dw::core::Arrays
import * from dw::core::Objects
output application/json
---
payload -- (payload map $ filter ( valuesOf( $.Errors ) some ( !isEmpty($) and ($ != null) and sizeOf($) >0)))
输出
[
{
"test": "1231test123","test2": "123test23232","test3": "12421test3","Errors": {
"test": "","test3": ""
}
}
]