Search code examples
jsontransformjolt

Append two string in Jolt based on condition


Input json:

{
  "accountType": "Admin",
  "id": "aaab-ccc-ddd-eeeAAA",
  "relationship": "DIRECT",
  "accountInfo": {
    "partyTypeCode": "PARTNER",
    "source": "Facebbok",
    "internalAccount": true,
    "category": "Father"
  }
}

output:

{
  "key":"aaab-ccc-ddd-eeeAAA~Admin",
  "relationship":"aaab-ccc-ddd-eeeAAA~Admin~0001"
}

here 0001 is the respective code for Father

2nd scenarios, Input JSON:

{
  "accountType": "User",
  "id": "aaab-ccc-ddd-eeeAAA",
  "relationship": "DIRECT",
  "accountInfo": {
    "partyTypeCode": "PARTNER",
    "source": "Facebbok",
    "internalAccount": true,
    "category": "Father"
  }
}

output:

{
  "key":"aaab-ccc-ddd-eeeAAA",
  "relationship":"aaab-ccc-ddd-eeeAAA~0001"
}

key should't contain append only when is admin should append. but 0001 should append to relationship

output1:

{
  "key":"aaab-ccc-ddd-eeeAAA~Admin",
  "relationship":"aaab-ccc-ddd-eeeAAA~Admin~0001"
}

output2:

{
  "key":"aaab-ccc-ddd-eeeAAA",
  "relationship":"aaab-ccc-ddd-eeeAAA~0001"
}

Solution

  • You can use the following transformation

    [
      { // conditional for the cases of "accountType" values
        "operation": "shift",
        "spec": {
          "accountType": {
            "Admin": {
              "@2,id|$": "key"
            },
            "*": {
              "@2,id": "key[]"
            }
          },
          "@accountInfo.category": "rel" // assign a new attribute for this value
        }
      },
      { // conditional for the cases of "accountInfo.category" values
        "operation": "shift",
        "spec": {
          "*": "&",
          "rel": {
            "Father": {
              "#~0001": "&2"
            },
            "*": {
              "# ": "&2"
            }
          }
        }
      },
      { // generate "relationship" attribute
        "operation": "modify-overwrite-beta",
        "spec": {
          "key": "=join(~,@(1,&))",
          "rel": "=concat(@(1,key),@(1,rel))",
          "relationship": "=trim(@(1,rel))" // remove trailing whitespace if exists
        }
      },
      { // get rid of the auxiliary attribute "rel"
        "operation": "remove",
        "spec": {
          "rel": ""
        }
      }
    ]