Search code examples
arraysjsonconcatenationelementjolt

jolt transformation to concatenate two elements of a JSON array


Hi I am novice to jolt transformation. I need help with following requirement.

input :

[
  {
    "firstName": "Fname1",
    "lastName": "Lname1",
    "state": "PA"
  },
  {
    "firstName": "Fname2",
    "lastName": "Lname2",
    "state": "VA"
  },
  {
    "firstName": "Fname3",
    "lastName": "Lname3",
    "state": "CA"
  }
]

expected output:

{
  "names": [
    "Fname1 Lname1",
    "Fname2 Lname2",
    "Fname3 Lname3"
  ],
  "states": [
    "PA",
    "VA",
    "CA"
  ]
}

Solution

  • You can use consecutive shift and modify transformation specs such as

    [
      {
        // combine names under common array while converting states to a unique array
        "operation": "shift",
        "spec": {
          "*": {
            "*Name": "names[&1].&1", // convert all ...Names to array of objects
            "state": "&s" // convert label of the array to state"s" while tiling the components of it
          }
        }
      },
      {
        // concatenate respective (F/L)names values
        "operation": "modify-overwrite-beta",
        "spec": {
          "names": {
            "*": {
              "*": "=join(' ',@(1,&))"
            }
          }
        }
      },
      {
        // convert array of objects to basic array
        "operation": "shift",
        "spec": {
          "n*": {
            "*": {
              "*": "&2[&1]"
            }
          },
          "*": "&" // else case, eg. "states" array
        }
      },
      {
        "operation": "sort"
      }
    ]
    

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

    enter image description here