json 嵌套数组的JOLT变换面临的问题

myzjeezk  于 2023-03-24  发布在  其他
关注(0)|答案(1)|浏览(85)

我有一个JSONinput

{
  "id": "Root_ID",
  "Item": [
    {
      "id": "ID_1",
      "characteristic": [
        {
          "name": "char1",
          "value": "PRE1"
        },
        {
          "name": "char2",
          "value": "2050-01-01"
        }
      ]
    },
    {
      "id": "ID_2",
      "characteristic": [
        {
          "name": "char1",
          "value": "PRE2"
        },
        {
          "name": "char2",
          "value": "2050-01-02"
        }
      ]
    }
  ]
}

需要使用Jolt转换规范将其转换为以下输出

{
  "id": "Root_ID",
  "Item": [
    {
      "id": "ID_1",
      "char1": "PRE1",
      "char2": "2050-01-01"
    },
    {
      "id": "ID_2",
      "char1": "PRE2",
      "char2": "2050-01-02"
    }
  ]
}

目前,我正在使用这个规范:

[
  {
    "operation": "shift",
    "spec": {
      "id": "id",
      "Item": {
        "*": {
          "characteristic": {
            "*": {
              "name": {
                "char1": {
                  "@(2,value)": "item[#3].char1"
                },
                "char2": {
                  "@(2,value)": "item[#3].char2"
                }
              }
            }
          }
        }
      }
    }
  }
]

这不能产生所需的结果。
你能帮我准备一个正确的规范来处理这个问题吗?

编辑:如果我想得到下面的JSON结果怎么办?

{
  "id": "Root_ID",
  "Item": [
    {
      "id": "ID_1",
      "char1": "PRE1"
    },
    {
      "id": "ID_2",
      "char1": "PRE2",
      "char2": "2050-01-02"
    }
  ]
}
kmbjn2e3

kmbjn2e31#

您可以使用以下shift转换规范,其中***@value***和***@name***相互匹配,例如

[
  {
    "operation": "shift",
    "spec": {
      "id": "&",
      "Item": {
        "*": {
          "id": "&2[&1].&",// you can reduce two levels based on the inner identifier 4,3 -> 2,1
          "char*": {
            "*": {
              "@value": "&4[&3].@name" // &4 copies the literal "Item" after going four levels up the tree, [&3] generates array-wise result(array of objects) after going three levels up the tree to reach the level of the indexes of the "Item" array
            }
          }
        }
      }
    }
  }
]

编辑:如果需要在除第一个对象以外的所有对象中返回**char2**,也可以使用以下规范:

[
  {
    "operation": "shift",
    "spec": {
      "id": "&",
      "Item": {
        "0": {// stands for the first index
          "id": "&2[&1].&",
          "char*": {
            "*": {
              "name": {
                "char1": {
                  "@2,value": "&6[&5].@3,name"
                }
              }
            }
          }
        },
        "*": {
          "id": "&2[&1].&",
          "char*": {
            "*": {
              "@value": "&4[&3].@name"
            }
          }
        }
      }
    }
  }
]

相关问题