将平面 JSON 转换为多个级别的嵌套 JSON

问题描述 投票:0回答:1

下面是我的JSON

[
  {
    "item_attr1": "abc",
    "item_attr2": "123",
    "item_attr3": "123",
    "item_id": "12345",
    "bucket_attr1": 1919,
    "bucket_attr2": "abc",
    "bucket_attr3": 1922,
    "bucket_attr4": "abc",
    "bucket_id_1": "abc",
    "bucket_id_2": "def",
    "bucket_id_3": "ghi",
    "articleattribute1": "abc",
    "articleattribute2": "abc",
    "articleattribute3": "2233",
    "article_id": "12345"
  },
  {
    "item_attr1": "abc",
    "item_attr2": "123",
    "item_attr3": "123",
    "item_id": "543421",
    "bucket_attr1": 1919,
    "bucket_attr2": "abc",
    "bucket_attr3": 1922,
    "bucket_attr4": "abc",
    "bucket_id_1": "abc",
    "bucket_id_2": "mef",
    "articleattribute1": "abc",
    "articleattribute2": "abc",
    "articleattribute3": "2233",
    "article_id": "12345"
  }
]

我需要按bucket_id_1、bucket_id_2和bucket_id_3进行分组,然后按article_id对该结果进行分组,以便输出看起来像这样

{
  "buckets": [
    {
      "bucket_id": "abc",
      "bucket_attr1": 1919,
      "bucket_attr2": "abc",
      "bucket_attr3": 1922,
      "bucket_attr4": "abc",
      "articles": [
        {
          "articleattribute1": "abc",
          "articleattribute2": "abc",
          "articleattribute3": "2233",
          "article_id": "12345",
          "items": [
            {
              "item_attr1": "abc",
              "item_attr2": "123",
              "item_attr3": "123",
              "item_id": "12345"
            },
            {
              "item_attr1": "abc",
              "item_attr2": "123",
              "item_attr3": "123",
              "item_id": "543421"
            }
          ]
        }
      ]
    }
  ]
}

我尝试编写 Jolt 转换和移位操作,并且还使用下面的站点来验证我的转换,但无法以我预期的格式获得结果

json jolt
1个回答
0
投票

您可以使用以下转换:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*_1": "buckets[0].&(0,1)",
        "bucket_attr*": "buckets[0].&",
        "article*": "buckets[0].articles[0].&",
        "item*": {
          "@": "buckets[0].articles[0].items[&2].&"
        }
      }
    }
  },
  {// pick single elements from each array those have identical repeating of them
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": {
          "*": "ONE",
          "articles": {
            "*": {
              "*": "ONE"
            }
          }
        }
      }
    }
  },
  {
    "operation": "sort"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.