Search code examples
jsonapache-nifijoltnotnull

Jolt concatenate two strings only if both are not null


I am trying to transform input data where I need to combine two values firstName and lastName into displayName if any of them are not null. If both are null, keep the input value of displayName in output value as it is. Sharing all scenarios below. Please advise. Thanks !

Scenario 1(both values are not null):

Input:

{
  "displayName": "random",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39",
  "firstName": "Ayan",
  "lastName": "Agrawal"
}

Output:

{
  "displayName": "Ayan Agrawal",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39"
}

Scenario 2(one of the values is null):

Input:

{
  "displayName": "random",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39",
  "firstName": null,
  "lastName": "Agrawal"
}

Output:

{
  "displayName": "Agrawal",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39"
}

Scenario 3(both values are null):

Input:

{
  "displayName": "random",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39",
  "firstName": null
  "lastName": null
}

Output:

{
  "displayName": "random",
  "Comments": "NotMentioned",
  "Team": "2",
  "modified_date": "2023-01-27 13:41:39"
}

Solution

  • You can use the trim function to remove surrounding whitespaces after concatenation and then add a conditional to check out whether the overall result is completely containing whitespaces or not through the contribution of size function such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "dN0": "=concat(@(1,firstName),' ',@(1,lastName))",
          "dN1": "=trim(@(1,dN0))",
          "dSz": "=size(@(1,dN1))"
        }
      },
      {
        "operation": "shift",
        "spec": {
          "dSz": {
            "0": { // both first and last names are null
              "@2,displayName": "displayName"
            },
            "*": { // else case
              "@2,dN1": "displayName"
            }
          },
          "Comments|Team|modified_date": "&"
        }
      }
    ]