Search code examples
jsonjolt

Jolt unnest arrays


Source JSON:

[
  {
    "dimensions": [
      {
        "id": "1546382552",
        "name": "BLOOM FACE MASK DAY SPA AM APOTHEKA"
      },
      {
        "id": "2024-12-01",
        "name": ""
      }
    ],
    "metrics": [
      364,
      20
    ]
  },
  {
    "dimensions": [
      {
        "id": "857640546",
        "name": "Vitamin A"
      },
      {
        "id": "2024-12-02",
        "name": ""
      }
    ],
    "metrics": [
      310,
      22
    ]
  }
]

From dimensions array:

  1. id from first object should be written as field sku and name as sku_name
  2. id from second object should be written as field date"

From metrics array:

  • first element in array should be written as session_view and second element as session_view_search

I tried (and failed):

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "dimensions": {
          "*": {
            "0": {
              "id": "[&2].sku",
              "name": "[&2].sku_name"
            },
            "1": {
              "id": "[&2].date"
            }
          }
        },
        "metrics": {
          "0": "session_view",
          "1": "session_view_search"
        }
      }
    }
  }
]

Finally I expect:

[
  {
    "sku": 1546382552,
    "sku_name": "BLOOM FACE MASK DAY SPA AM APOTHEKA",
    "date": "2024-12-01",
    "session_view": 364,
    "session_view_search": 20
  },
  {
    "sku": 857640546,
    "sku_name": "Vitamin A",
    "date": "2024-12-02",
    "session_view": 310,
    "session_view_search": 22
  }
]

Solution

  • A breakdown should be taken from outermost level along with removing the extra middle nesting level such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "dimensions": {
              "0": {
                "id": "&3.sku",
                "name": "&3.sku_name"
              },
              "1": {
                "id": "&3.date"
              }
            },
            "metrics": {
              "0": "&2.session_view",
              "1": "&2.session_view_search"
            }
          }
        }
      },
      {//get rid of the object keys
        "operation": "shift",
        "spec": {
          "*": "[]"
        }
      }
    ]
    

    the demo on the site Jolt Transform Demo Using v0.1.1 is :

    enter image description here