编写通用JOLT转换规范:嵌套JSON转多行扁平JSON
通用JOLT转换规范:嵌套JSON转多行扁平JSON
需求
需要编写一份通用JOLT转换规范,可同时处理单个嵌套JSON对象或嵌套JSON对象数组,将其转换为多行扁平JSON:每个test数组元素对应一条扁平记录,保留上层的Id、Name、records.aaa字段,test内的字段以records.test.xxx格式命名。
输入数据1(单个对象)
{ "Id": "123", "Name": "tets", "records": [ { "aaa": "123", "test": [ { "zzz": 987, "yyy": 123 }, { "zzz": 345, "yyy": 678 } ] } ] }
输入数据2(对象数组)
[ { "Id": "123", "Name": "tets", "records": [ { "aaa": "123", "test": [ { "zzz": 987, "yyy": 123 }, { "zzz": 345, "yyy": 678 } ] } ] }, { "Id": "1234", "Name": "tets2", "records": [ { "aaa": "123", "test": [ { "zzz": 987, "yyy": 123 }, { "zzz": 345, "yyy": 678 } ] }, { "aaa": "12345", "test": [ { "zzz": 456, "yyy": 567 } ] } ] } ]
输入数据1期望输出
[ { "Id": "123", "Name": "tets", "records.aaa": "123", "records.test.zzz": 987, "records.test.yyy": 123 }, { "Id": "123", "Name": "tets", "records.aaa": "123", "records.test.zzz": 345, "records.test.yyy": 678 } ]
输入数据2期望输出
[ { "Id": "123", "Name": "tets", "records.aaa": "123", "records.test.zzz": 987, "records.test.yyy": 123 }, { "Id": "123", "Name": "tets", "records.aaa": "123", "records.test.zzz": 345, "records.test.yyy": 678 }, { "Id": "1234", "Name": "tets2", "records.aaa": "123", "records.test.zzz": 987, "records.test.yyy": 123 }, { "Id": "1234", "Name": "tets2", "records.aaa": "123", "records.test.zzz": 345, "records.test.yyy": 678 }, { "Id": "1234", "Name": "tets2", "records.aaa": "12345", "records.test.zzz": 456, "records.test.yyy": 567 } ]
通用JOLT转换规范
[ // 统一输入格式:将单个对象包装为数组,兼容两种输入类型 { "operation": "shift", "spec": { "*": { "@": "[]" }, "Id": { "@": "[0].&" }, "Name": { "@": "[0].&" }, "records": { "@": "[0].&" } } }, // 多层展开并映射字段:逐层展开数组,向上引用上层字段并重命名嵌套字段 { "operation": "shift", "spec": { "*": { "records": { "*": { "test": { "*": { "@(3,Id)": "Id", "@(3,Name)": "Name", "@(2,aaa)": "records.aaa", "zzz": "records.test.zzz", "yyy": "records.test.yyy" } } } } } } }, // 整理结果为数组格式 { "operation": "shift", "spec": { "*": { "@": "[]" } } } ]
规范说明
- 统一输入格式:第一个shift操作把单个对象转为长度为1的数组,确保后续处理逻辑对两种输入类型一致。
- 多层展开与字段映射:第二个shift操作逐层展开顶层数组、
records数组、test数组,通过@(n,key)语法向上引用上层的Id、Name和当前records的aaa字段,同时将test内的字段重命名为带路径的键名。 - 结果整理:最后一个shift操作将分散的记录重新组合为数组,得到最终的多行扁平结构。
内容的提问来源于stack exchange,提问作者Sumit Manna
相关产品推荐
相关产品推荐

