jsonjolt

Replace empty string with null via JOLT SPEC


within a JSON I have several values which represent an empty string (they could be on highest level or one level below).

Input:

{
  "test": "value1",
  "test2": "",
  "test3": "value2",
  "test3_extra": {
    "test3_extra1": "",
    "test3_extra2": "random"
  }
}

Whenever an empty string occurs, I would like to replace it by null.

Desired Output:

{
  "test": "value1",
  "test2": null,
  "test3": "value2",
  "test3_extra": {
    "test3_extra1": null,
    "test3_extra2": "random"
  }
}

Can someone give me a hint on how to do this? Thanks in advance for your support.


Solution

  • You can use following shift transformation spec in which the "" values should be used on the left-hand-side like keys such as :

    [
      {
        "operation": "shift",
        "spec": {
          "*": {//outermost attributes
            "": "&1",
            "*": {
              "@1": "&2"
            }
          },
          "*_extra": {//one-level nested attributes
            "*": {
              "": "&2.&1",
              "*": {
                "@1": "&3.&2"
              }
            }
          }
        }
      }
    ]
    

    the demo on the site Jolt Transform Demo Using v0.1.1 is :

    enter image description here