Search code examples
jsonjolt

Jolt move values from array to top level


I have a JSON like:

[
  {
    "id": 1015380,
    "type": "campaign",
    "stats": [
      {
        "month": "2023-07",
        "spent": "3116.90",
        "impressions": 17783,
        "clicks": 78
      },
      {
        "month": "2023-08",
        "spent": "1490.36",
        "impressions": 6721,
        "clicks": 17
      }
    ]
  },
  {
    "id": 1015695,
    "type": "campaign",
    "stats": [
      {
        "month": "2023-08",
        "spent": "1490.36"
      }
    ]
  }
]

I want to unnest stats array to top level and get result like this:

enter image description here

Tried with script below, but it stores values from stats as arrays:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "stats": {
          "*": {
            "@(2,id)": "[&3].id",
            "*": "[&3].&"
          }
        }
      }
    }
  }
]

How to fix it?


Solution

  • You can use the following shift transformation spec

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "stats": {
              "*": {
                "@2,id": "&3_&1.id",
                "*": "&3_&1.&"
              }
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": ""
        }
      }
    ]
    

    Only the value of the indexes of the outermost objects are walked in the current case, while this suggested case will walk through the indexes of the stats array(eg. &1) as well to group by two different identifiers to generate ındependent objects within an array

    the demo on the site http://jolt-demo.appspot.com/ is :

    enter image description here