使用Jolt将变更日志JSON转换为起止格式的技术求助
问题:用Jolt将变更日志JSON转换为起止格式是否可行?求转换Spec
我已通过shift操作将原始JSON精简为当前格式,但后续推进遇到瓶颈,希望用Jolt把下述变更日志格式的JSON转换成From/To(起止)格式,请问是否可行?能否提供对应的转换Spec?
输入JSON:
{ "fields": { "status": "Done", "created": "2023-02-22" }, "history": [ { "created": "2023-02-27", "items": [ { "field": "Status", "fromString": "In Testing", "toString": "Done" }, { "field": "Priority", "fromString": "P2", "toString": "P1" } ] }, { "created": "2023-02-26", "items": [ { "field": "Status", "fromString": "In Progress", "toString": "In Testing" } ] }, { "created": "2023-02-25", "items": [ { "field": "Status", "fromString": "New", "toString": "In Progress" } ] }, { "created": "2023-02-24", "items": [ { "field": "Status", "fromString": "In Progress", "toString": "New" } ] }, { "created": "2023-02-23", "items": [ { "field": "Status", "fromString": "New", "toString": "In Progress" } ] } ] }
期望输出:
{ "statusHistory": [ { "status": "New", "fromDate": "2023-02-22", "toDate": "2023-02-23" }, { "status": "In Progress", "fromDate": "2023-02-23", "toDate": "2023-02-24" }, { "status": "New", "fromDate": "2023-02-24", "toDate": "2023-02-25" }, { "status": "In Progress", "fromDate": "2023-02-25", "toDate": "2023-02-26" }, { "status": "In Testing", "fromDate": "2023-02-26", "toDate": "2023-02-27" }, { "status": "Done", "fromDate": "2023-02-27", "toDate": "" } ] }
可行,以下是对应的Jolt转换Spec
这个需求完全可以通过Jolt实现,核心思路是先整合所有状态节点的时间与状态值,再按时间顺序关联起止日期。以下是完整的Jolt Spec:
[ // 第一步:提取初始状态、创建时间,以及历史中所有Status变更记录 { "operation": "shift", "spec": { "fields": { "created": "temp[0].date", "status": "temp[0].toStatus" }, "history": { "*": { "created": "temp[#2].date", "items": { "*": { "field": { "Status": { "@(2,fromString)": "temp[#4].fromStatus", "@(2,toString)": "temp[#4].toStatus" } } } } } } } }, // 第二步:按date升序排序,确保时间顺序正确 { "operation": "sort", "spec": { "temp": ["date"] } }, // 第三步:构建状态历史的起止结构 { "operation": "shift", "spec": { "temp": { "*": { "0": { "toStatus": "statusHistory[0].status", "date": "statusHistory[0].fromDate", "@(1,1.date)": "statusHistory[0].toDate" }, "*": { "toStatus": "statusHistory[&1].status", "date": "statusHistory[&1].fromDate", "@(1,(&1+1).date)": "statusHistory[&1].toDate" } } } } }, // 第四步:给最后一条记录的toDate设置默认空字符串 { "operation": "default", "spec": { "statusHistory": { "*": { "toDate": "" } } } } ]
各步骤说明:
- Shift(提取数据):将初始创建时间、初始状态,以及历史中所有
Status类型的变更记录提取到临时列表temp中,每条记录包含日期、变更前状态、变更后状态。 - Sort(排序):对
temp列表按日期升序排列,保证时间线的顺序正确。 - Shift(构建历史):遍历排序后的
temp列表,将每个节点的变更后状态作为当前状态,自身日期作为fromDate,下一个节点的日期作为toDate,形成起止结构。 - Default(补全空值):为最后一条状态记录的
toDate设置空字符串,因为当前状态尚未结束。
内容的提问来源于stack exchange,提问作者Nathan Stout
相关产品推荐
相关产品推荐

