Search code examples
javajsonjolt

Default JSON property if not exists using Jolt


I want to set a default value only if the JSON property not exists.

For example, below is my Jolt spec :

[
  {
    "operation": "modify-default-beta",
    "spec": {
      "lastName": "[empty]"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "firstName": "firstName",
      "lastName": "lastName"
    }
  }
]

When input is :

{
  "firstName": "John"
}

the output is as expected :

{
  "firstName" : "John",
  "lastName" : "[empty]"
}

On the other hand when input is :

{
  "firstName": "John",
  "lastName": null
}

I'm expecting the output is same as the input :

{
  "firstName": "John",
  "lastName": null
}

is there anyway to default only when property not exists regardless of it value. Thanks


Solution

  • First of all the shift transformation is not needed. You can use an isNull function within a modify transformation such as

    [
      {
        "operation": "modify-default-beta",
        "spec": {
          "lastName": ["=isNull(@(1,&))", "[empty]"]
        }
      }
    ]
    

    where

    • @(1,&) represents the value of the current attribute, eg. "lastName"(the ampersand stnds for the lastName literal)
    • if the function is able to run, then the value null returns directly, otherwise the second argument "[empty]" returns