Search code examples
jsonjolt

Unnest arrays and add array name as additional field


Source JSON:

{
  "dimensions": [
    {
      "apiName": "achievementId",
      "uiName": "Achievement ID"
    },
    {
      "apiName": "adFormat",
      "uiName": "Ad format",
      "category": "Publisher"
    }
  ],
  "metrics": [
    {
      "apiName": "active1DayUsers",
      "uiName": "1-day active users"
    },
    {
      "apiName": "active28DayUsers",
      "uiName": "28-day active users"
    }
  ],
  "name": "properties/317728157/metadata"
}

Expected:

[
   {
      "apiName":"achievementId",
      "uiName":"Achievement ID",
      "metadata_object":"dimensions"
   },
   {
      "apiName":"adFormat",
      "uiName":"Ad format",
      "category":"Publisher",
      "metadata_object":"dimensions"
   },
   {
      "apiName":"active1DayUsers",
      "uiName":"1-day active users",
      "metadata_object":"metrics"
   },
   {
      "apiName":"active28DayUsers",
      "uiName":"28-day active users",
      "metadata_object":"metrics"
   }
]

I should unnest both arrays: dimensions and metrics. For each object from the array dimensions I should add the field metadata_object=dimensions. For each object from array metrics - metadata_object=metrics. I can do it with JOLT in a separate way like this:

[
  {
    "operation": "shift",
    "spec": {
      "dimensions": {
        "*": {
          "*": "[&1].&"
        }
      }
    }
  },
  {
    "operation": "default",
    "spec": {
      "*": {
        "metadata_object": "dimensions"
      }
    }
  }
]

But how to combine both arrays with one JOLT?


Solution

  • You can use this spec:

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": "&2.[&1].&",
              "$1": "&2.[&1].metadata_object"
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": ""
          }
        }
      }
    ]