JOLT轮班转换:收集所有级别的所有项目,而不知道有多少级别



我正在尝试使用Jolt转换来转换JSON,在这里寻找一些输入。我正在尝试将所有级别的所有项目放入一个数组中。

我的目标是获得一个包含所有项的数组,而不知道json中有多少级别

以下是我的输入和预期输出:

如果我有3个级别:

输入

{
"id": 11,
"item": [
{
"id": "11_1",
"item": [
{
"id": "11_1_1",
"item": [
{
"id": "11_1_1_1"
}
]
},
{
"id": "11_1_2",
"item": [
{
"id": "11_1_2_1"
}
]
}
]
}
]
}

预期输出

[
{
"id": "11_1"
},
{
"id": "11_1_1"
},
{
"id": "11_1_1_1"
},
{
"id": "11_1_2"
},
{
"id": "11_1_2_1"
}
]

如果我有两个级别:

输入

{
"id": 11,
"item": [
{
"id": "11_1",
"item": [
{
"id": "11_1_1"
},
{
"id": "11_1_2"
}
]
}
]
}

预期输出

[
{
"id": "11_1"
},
{
"id": "11_1_1"
},
{
"id": "11_1_2"
}
]

我试着写这样的东西:

[
{
"operation": "shift",
"spec": {
"item": {   //to cover the second level
"*": "item"
}
}
},
{
"operation": "shift",
"spec": {
"item": {
"*": {    //to cover the 3td level
"item": {
"*": "item"
}
}
}
}
}
]

结果为null,如果我分别运行每个转换,我会在适用的情况下得到结果你能帮我写一个简单的规范吗?

如果输入最多有3个级别,那么使用这个规范

[
{
"operation": "shift",
"spec": {
"item": {
"*": {
"id": "&",
"item": {
"*": {
"id": "&",
"item": {
"*": {
"id": "&"
}
}
}
}
}
}
}
},
{
"operation": "shift",
"spec": {
"id": {
"*": "[#1].&1"
}
}
}
]

以便仅使用这一个来处理这两种情况。如果还需要一个级别,则添加

,
"item": {
"*": {
"id": "&"
}
}

就在最内部之后

"id": "&"

编辑:如果您有id以外的其他属性,如下面的输入示例中所述

{
"id": 11,
"item": [
{
"id": "11_1",
"quantity": 1,
"action": "add",
"state": "x",
"item": [
{
"id": "11_1_1",
"quantity": 2,
"action": "drop",
"state": "y"
},
{
"id": "11_1_2",
"quantity": 3,
"action": "modify",
"state": "z"
}
]
}
]
}

而不仅仅是一点修改就可以处理你的新案例:

[
{
"operation": "shift",
"spec": {
"item": {
"*": {
"*": "&",
"item": {
"*": {
"*": "&",
"item": {
"*": {
"*": "&"
}
}
}
}
}
}
}
},
{
"operation": "shift",
"spec": {
"*": {
"*": "[#1].&1"
}
}
}
]

将生成:

[
{
"id": "11_1",
"quantity": 1,
"action": "add",
"state": "x"
},
{
"id": "11_1_1",
"quantity": 2,
"action": "drop",
"state": "y"
},
{
"id": "11_1_2",
"quantity": 3,
"action": "modify",
"state": "z"
}
]

使用库Josson实现无限级别的解决方案。

https://github.com/octomix/josson

反序列化

Josson josson = Josson.fromJsonString(
"{" +
"  "id": 11," +
"  "item": [" +
"    {" +
"      "id": "11_1"," +
"      "quantity": 1," +
"      "action": "add"," +
"      "state": "x"," +
"      "item": [" +
"        {" +
"          "id": "11_1_1"," +
"          "quantity": 2," +
"          "action": "drop"," +
"          "state": "y"" +
"        }," +
"        {" +
"          "id": "11_1_2"," +
"          "quantity": 3," +
"          "action": "modify"," +
"          "state": "z"" +
"        }" +
"      ]" +
"    }" +
"  ]" +
"}");

转换

JsonNode node = josson.getNode("item.cumulateCollect(field(item:), item)");
System.out.println(node.toPrettyString());

语句field(item:)从当前对象中删除字段item
cumulateCollect()的第二个自变量表示下一个级别。在这种情况下是item

输出

[ {
"id" : "11_1",
"quantity" : 1,
"action" : "add",
"state" : "x"
}, {
"id" : "11_1_1",
"quantity" : 2,
"action" : "drop",
"state" : "y"
}, {
"id" : "11_1_2",
"quantity" : 3,
"action" : "modify",
"state" : "z"
} ]

最新更新