Jolt transformation chunk flat array into pairs of two

Viewed 34

I am trying to group pairs of two in a flat list, note that the amount of pairs can be variable (e.g. 0, 2, 4, 6 and so on).

See intended input/output.

Input:

{
  "coordinates": [
    1.1,
    5.1,
    1.2,
    5.3,
    1.3,
    5.5
  ]
}

Output:

{
  "coordinates": [
    [1.1, 5.1],
    [1.2, 5.3],
    [1.3, 5.5],  
  ]
}

Is this something that can be easily achieved using a Jolt transformation?

1 Answers

Yes, you can achieve it by using successive transformations such as

[
 //index each values seperately
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&1.&"
      }
    }
  },
 // convert values to string type so as to prevent the issue of truncation of decimal parts of those values
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "*": "=toString(@(1,&))"
      }
    }
  },
 // exchange key-value pairs
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "$": "&2.@(0)"
        }
      }
    }
  },
  {
 // increment the values by 1 in order to prepare them for modular arithetic logic held in the following steps
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "*": "=intSum(@(1,&),1)"
      }
    }
  },
  {
 // pairs means to have two components, then need to divide the values by 2 along with rounding to the nearest grater integer
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "*": "=divideAndRound(0,@(1,&),2)"
      }
    }
  },
  {
  // exchange key-value pairs back while keeping the name of the object("coordinates")
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "$": "&2.@(0)"
        }
      }
    }
  },
  {
 // dissipate each component of the list to their proper place
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&1[]"
      }
    }
  }
]
Related