Search code examples
jsonjolt

How to remove a null element from an array using the Jolt Transformation specification?


I want to remove null elements from the array using the Jolt spec.

Example:

Input:

{
  "arrayOne": [
    null,
    {
      "key1": "value1",
      "key2": "value2"
    }
  ]
}

Required output:

{
  "arrayOne": [
    {
      "key1": "value1",
      "key2": "value2"
    }
  ]
}

I tried using "recursivelySquashNulls" but that did not work.

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=recursivelySquashNulls"
    }
  }
]

Solution

  • You can use the following shift transformations in first of which the related nodes are taken without square brackets, eg. &2, &1, & such as :

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": "&2.&1.&" //&2 represents the literal "arrayOne"
                             //&1 represents the indexes of the wrapper array "arrayOne"
                             //&  represents the values of the leaf nodes
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": "&1[]"
          }
        }
      }
    ]
    

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

    enter image description here