JOLT转换需求:按station分组JSON并调整数据结构
JOLT JSON分组转换解决方案
输入JSON
[ { "table": 0, "_time": "2024-05-08T10:33:48.14Z", "_value": 40976, "parameter": "A", "station": "ABC", "stationName": "AABBCC" }, { "table": 0, "_time": "2024-05-08T10:34:33.372Z", "_value": 42009, "parameter": "A", "station": "ABC", "stationName": "AABBCC" }, { "table": 1, "_time": "2024-05-08T10:33:48.141Z", "_value": 22091, "parameter": "B", "station": "XYZ", "stationName": "XXYYZZ" }, { "table": 1, "_time": "2024-05-08T10:34:10.231Z", "_value": 21968, "parameter": "B", "station": "XYZ", "stationName": "XXYYZZ" } ]
优先期望输出
[ { "stationName": "AABBCC", "content": [ { "table": 0, "_time": "2024-05-08T10:33:48.14Z", "_value": 40976, "parameter": "A", "station": "ABC" }, { "table": 0, "_time": "2024-05-08T10:34:33.372Z", "_value": 42009, "parameter": "A", "station": "ABC" } ] }, { "stationName": "XXYYZZ", "content": [ { "table": 1, "_time": "2024-05-08T10:33:48.141Z", "_value": 22091, "parameter": "B", "station": "XYZ" }, { "table": 1, "_time": "2024-05-08T10:34:10.231Z", "_value": 21968, "parameter": "B", "station": "XYZ" } ] } ]
转换需求
- 按
station字段将数据分组到不同数组 - 将
stationName字段移到数组外,提升一级 - 最终结果为数组形式,且规则需通用(
station值不固定)
已有尝试及输出
尝试的JOLT规则
[ { "operation": "shift", "spec": { "*": "@station" } }, { "operation": "shift", "spec": { "@": "[]" } } ]
得到的输出
[ { "ABC": [ { "table": 0, "_time": "2024-05-08T10:33:48.14Z", "_value": 40976, "parameter": "A", "station": "ABC", "stationName": "AABBCC" }, { "table": 0, "_time": "2024-05-08T10:34:33.372Z", "_value": 42009, "parameter": "A", "station": "ABC", "stationName": "AABBCC" } ], "XYZ": [ { "table": 1, "_time": "2024-05-08T10:33:48.141Z", "_value": 22091, "parameter": "B", "station": "XYZ", "stationName": "XXYYZZ" }, { "table": 1, "_time": "2024-05-08T10:34:10.231Z", "_value": 21968, "parameter": "B", "station": "XYZ", "stationName": "XXYYZZ" } ] } ]
解决方案
优先期望的输出格式完全可实现,以下是通用的JOLT转换规则:
[ { // 第一步:按station分组,提取stationName并将其他字段存入content数组 "operation": "shift", "spec": { "*": { "stationName": "@(1,station).stationName", "*": "@(1,station).content[&1].&" } } }, { // 第二步:将分组后的对象转为数组元素 "operation": "shift", "spec": { "*": { "stationName": "[&1].stationName", "content": "[&1].content" } } }, { // 第三步:确保stationName只保留唯一值(同组内所有条目stationName一致) "operation": "cardinality", "spec": { "*": { "stationName": "ONE" } } } ]
规则说明
- 第一个shift操作:通过
@(1,station)按station值分组,将每个条目的stationName存入对应分组的顶级字段,其余字段存入content数组。 - 第二个shift操作:将分组后的键值对转换为数组元素,每个元素包含
stationName和content。 - cardinality操作:去除
stationName的重复值(同组内所有原始条目的stationName一致,仅保留第一个值)。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

