jsonjolt

Jolt tranformation: how to check for null or empty value in array and if empty populate with another value


I have three scenarios:

Scenario 1: When Fee1 has a value and Fee2 is "", output attribute FinalFee should have Fee1 value Scenario 2: When Fee1 is "" and Fee2 has a value, output attribute FinalFee should have Fee2 value Scenario 1: When Fee1 has a value and Fee2 has a value, output attribute FinalFee should have Fee1 value

Input:

{
  "school": [
    {
      "schoolCode": ["SH","MA","KR"],
      "fee1": [3,"",5],
      "fee2": ["",10,15]
    }
  ]
}

Expected Output:

{
  "school": [
    {
      "schoolCode": "SH",
      "finalFee": 3
    },
    {
      "schoolCode": "MA",
      "finalFee": 10
    },
    {
      "schoolCode": "KR",
      "finalFee": 5
    }
  ]
}

All 3 scenarios are mentioned in the input, how to write the jolt operation for this. ifNull and ifEmpty functions did not work.

This is the spec operation I am trying to update

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "school": {
        "*": {
          "schoolCode": {
            "*": {
              "@": [
                "school.[#2].schoolCode"
              ]
            }
          },
          "fee1": {
            "*": {
              "@": [
                "school.[#2].finalFee" 
              ]
            }
          },
           "fee2": {
            "*": {
              "@": [
                "school.[#2].finalFee" 
              ]
            }
          }
        }
      }
    }
  }
]

Solution

  • You can use the folowing transformation spec :

    [
      {/Rearrange the elements to resemble the expected output 
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "*": {
                "*": "&3[&].&1"//&3  represents the key "school" 
                               //[&] produces arraywise results along with the index values, eg. 0,1,2 
                               //&1  represents the keys of the arrays
              }
            }
          }
        }
      },
      {//keep fee1 if it's an integer, otherwise return fee2   
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "*": {
              "finalFee": ["=toInteger(@(1,fee1))", "=(@(1,fee2))"] //Elvis Operator
            }
          }
        }
      },
      {//get rid of the unneeded attributes
        "operation": "remove",
        "spec": {
          "*": {
            "*": {
              "fee*": ""
            }
          }
        }
      }
    ]
    

    Refer this page for Elvis Operator