首页 > 文章列表 > 令人意外的结果:Go Kazaam 转换返还

令人意外的结果:Go Kazaam 转换返还

423 2024-02-07
问题内容

我使用 kazaam 模块来定义 json 转换。 https://github.com/qntfy/kazaam

这些是我的规则:

"rules": [
        {
            "operation": "shift",
            "spec": {
                "Shift": "instruction.context.example1"
            }
        },
        {
            "operation": "concat",
            "spec": {
                "sources": [
                    {
                        "path": "instruction.context.example1"
                    },
                    {
                        "path": "instruction.context.example2"
                    }
                ],
                "targetPath": "Concat",
                "delim": "_"
            }
        },
        {
            "operation": "coalesce",
            "spec": {
                "Coalesce": [
                    "instruction.context.example3[0].id"
                ]
            }
        }
    ]

应用于此 json:

{
    "instruction": {
        "context": {
            "example1": "example1 value",
            "example2": "example2 value",
            "example3": [
                {
                    "id": "example3_1_value"
                },
                {
                    "id": "example3_2_value"
                },
                {
                    "id": "example3_3_value"
                }
            ]
        }
    }
}

结果是这样的:

{
    "Shift": "example1 value",
    "Concat": "null_null"
}

因此第一个操作有效,第二个操作返回 null_null,而第三个操作则不会出现。


正确答案


这些规则会依次应用。第一个规则产生的结果将作为第二个规则的输入,依此类推,它们是链接在一起的。因此,您首先转换会产生一个对象:

{
  "Shift": "example1 value"
}

当上述内容作为第二个操作的输入时 - 您将获得 null 值,因为您所引用的字段 - 不存在。
您可以尝试将第一条规则更改为:

{
            "operation": "shift",
            "spec": {
                "Shift": "instruction.context.example1",
                "instruction.context.example1": "instruction.context.example1",
                "instruction.context.example2": "instruction.context.example2"
            }
        },

看看它的效果。