Search code examples
jsonjolt

JOLT transformation using condition on different keys


Can you please assist me with the below as I am new to JOLT Transformation.

I have an input JSON in the below format.

My requirement is to check

  • if the "id" inside "playBot" is PROGRAM , then include "billID" : "1800-A" inside "header".
  • if "id" is not PROGRAM (any other value other than PROGRAM) , then do not include billID.

Input :

{
  "playBot" : {
    "id" : "PROGRAM",
    "source" : "TestUser",
    "dateTime" : "01-09-2024 13:24:42"
  },
  "header" : {
    "activityID" : "4100",
    "memberID" : "User-ABC",
    "billID" : "1800-A"
  }
}

Desired Output for 1st case :

{
  "playBot" : {
    "id" : "PROGRAM",
    "source" : "TestUser",
    "dateTime" : "01-09-2024 13:24:42"
  },
  "header" : {
    "activityID" : "4100",
    "memberID" : "User-ABC",
    "billID" : "1800-A"
  }
}

Desired Output for 2nd case :

{
  "playBot" : {
    "id" : "TEST",
    "source" : "TestUser",
    "dateTime" : "01-09-2024 13:24:42"
  },
  "header" : {
    "activityID" : "4100",
    "memberID" : "User-ABC"
  }
}

Solution

  • You can use this shift transformation spec which includes conditional logic within the lines starting from the node "header"

    [
      {
        "operation": "shift",
        "spec": {
          "*": "&", // "playBot" object
          "header": {
            "billID": {
              "@2,playBot.id": { // go 2 levels up the tree to grab the value of "playBot.id"
                "PROGRAM": {
                  "@2": "&4.billID" // &4 prefixes the attribute by "header" by going 4 levels up the tree
                                    // while copying the value of billID through using @2
                },
                "": "" // else case in order the attribute "billID" to be vanished 
              }
            },
            "*": "&1.&" // &1 prefixes the attribute by "header" 
          }
        }
      }
    ]