DataWeave中转换Unix时间戳键并查找最大日期时间值
问题
给定以下以Unix毫秒时间戳为键的JSON数据:
{ "test": { "1669587277000": 90, "1669585177000": 6, "1669589077000": 9, "1669580977000": 0 } }
已知单个时间戳转DateTime的DataWeave表达式:
as DateTime {unit: "milliseconds"} as String {format: 'yyyy-MM-dd hh:mm:ss:SSS'}
需要实现:将所有键转换为DateTime格式,并找出最大日期时间对应的键值对,期望输出如下:
[ { "2022-11-27 10:14": 90 } ]
解决方案
使用以下DataWeave 2.0表达式即可完成需求:
%dw 2.0 output application/json --- payload.test pluck ((val, tsKey) -> { formattedDate: tsKey as Number as DateTime {unit: "milliseconds"} as String {format: 'yyyy-MM-dd hh:mm'}, value: val }) orderBy ((item) -> -item.formattedDate as DateTime) [0] mapObject ((itemVal, itemKey) -> { (itemVal.formattedDate): itemVal.value }) wrapInArray
步骤说明:
- 提取键值对:用
pluck将test对象的键值对转为数组,便于逐个处理时间戳键 - 转换时间戳格式:把字符串类型的时间戳转为数字,再转换为DateTime,最后格式化为
yyyy-MM-dd hh:mm的字符串(匹配期望输出格式) - 筛选最大日期:通过
orderBy按日期时间降序排序,取数组第一个元素,即为最大日期对应的条目 - 调整输出结构:用
mapObject将数据结构转为目标键值对格式,再用wrapInArray包装成数组
内容的提问来源于stack exchange,提问作者Anonim
相关产品推荐
相关产品推荐

