我有一个输入有效负载,我需要直接传递给输出,除了我需要转换的特定日期属性。这些日期属性可以是有效负载内的任何位置。即,
我已使用下面的数据编码解决了上面的案例1和2。但是,我对案例3和案件4有点困惑。非常感谢这方面的任何指示。谢谢!
输入有效载荷:
{
"key1":"value1",
"key2":"value2",
"arrayList1":[
{
"key3":"value3",
"datefield_1":"13/01/2006",
"datefield_2":"15/06/1980",
"arrayList2":[
{
"key4":"value4",
"datefield_3":"13/01/2000",
"datefield_4":"15/06/2003",
"arrayList2":[
{
"key5":"value5",
"datefield_5":"30/01/2000",
"datefield_6":"14/06/2003"
}
]
}
]
},
{
"key6":"value6",
"datefield_7":"20/02/2000"
}
]
}
Dataweave代码:
%dw 1.0
%output application/json
%var keysToUpdate = ['datefield_1', 'datefield_2', 'datefield_3', 'datefield_4', 'datefield_5', 'datefield_6', 'datefield_7']
%function transformDateFormat(inputDate) inputDate as :date {format: "dd/MM/yyyy"} as :date {format: "yyyy-MM-dd"}
%function findKey(key) keysToUpdate contains key
%function changePayload(input) input mapObject ({
($$): changePayload($) when $ is :object otherwise $
} unless findKey($$ as :string) otherwise {
($$): transformDateFormat($)
})
---
changePayload (payload)
答案 0 :(得分:1)
带有一些递归的match
运算符在这里会很有帮助。
试一试。我创建了一个函数applyToValuesWhenKey
,它将输入值作为e
,一个应用于值为fn
的函数,以及一个返回一个布尔值的函数,该布尔函数将指示是否为不要将fn
应用于名为predicate
的值。它使用递归和match
运算符循环遍历数据,应用map
,mapObject
,或者仅返回给定值,具体取决于当前值是否为对象,数组,或其他任何东西。剩下的就是你的代码:
%dw 1.0
%output application/json
%var input = {
"key1":"value1",
"key2":"value2",
"arrayList1":[
{
"key3":"value3",
"datefield_1":"13/01/2006",
"datefield_2":"15/06/1980",
"arrayList2":[
{
"key4":"value4",
"datefield_3":"13/01/2000",
"datefield_4":"15/06/2003",
"arrayList2":[
{
"key5":"value5",
"datefield_5":"30/01/2000",
"datefield_6":"14/06/2003"
}
]
}
]
},
{
"key6":"value6",
"datefield_7":"20/02/2000"
}
]
}
%var keysToUpdate = [ 'datefield_1', 'datefield_2', 'datefield_3', 'datefield_4', 'datefield_5', 'datefield_6', 'datefield_7' ]
%function applyToValuesWhenKey( e, fn, predicate )
e match {
:array -> $ map applyToValuesWhenKey( $, fn, predicate ),
:object -> $ mapObject ( ( v, k ) -> {
( k ): fn( v )
} when predicate( k ) otherwise {
( k ): applyToValuesWhenKey( v, fn, predicate )
}
),
default -> $
}
%function transformDateFormat( date )
date as :date { format: "dd/MM/yyyy" } as :date { format: "yyyy-MM-dd" }
%function transformDates( input )
applyToValuesWhenKey( input,
transformDateFormat,
( ( key ) -> keysToUpdate contains ( key as :string ) ) )
---
transformDates( input )