Search code examples
jsontransformationjolt

Jolt Conditional Flag Based on JSON Fields


I have a JSON input as below

Scenario 1:

{
  "accountType": "Admin",
  "accountInformation": {
    "user": "internal",
    "source": "Facebook",
    "internalAccount": "false"
  }
}

output.json

{
  "userFlag":true
}

I need to derive a userFlag in Java, which should be true only when the user is "internal" and the source is "Facebook". If the user is null or the source is other than "Facebook," the userFlag should be set to the value of internalAccount.

Scenario 2:

{
  "accountType": "Admin",
  "accountInformation": {
    "user": "internal",
    "source": "Google",
    "internalAccount": "false"
  }
}

output.json

{
  "userFlag":false
}
[
  {
    "operation": "shift",
    "spec": {
      "accountInformation": {
        "source": {
          "Facebook": {
            "#true": "sourceFlag"
          }
        },
        "user": {
          "internal": {
            "#true": "userInternalFlag"
          }
        },
        "internalAccount": "userFlag"
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "result": "=equals(@(1,sourceFlag),@(1,userInternalFlag))"
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "userFlag": "=equals(@(1,result), 'true')"
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "userFlag": "=toBoolean(@(1,userFlag))"
    }
  },
  {
    "operation": "remove",
    "spec": {
      "sourceFlag": "",
      "userInternalFlag": "",
      "result": ""
    }
  }
]

producing the output:

{
  "userFlag" : true
}

but when for this input shouldn't produce value as

{
  "accountType": "Admin",
  "accountInformation": {
    "user": "",
    "source": "Facebook",
    "internalAccount": false
  }
}

actual:

{
  "userFlag" : true
}

expected:

{
  "userFlag" : false
}

Solution

  • You can use the below Jolt spec

    [
      {
        "operation": "modify-default-beta",
        "spec": {
          "accountInformation": {
            "user|source": "null"
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "accountInformation": {
            "user": {
              "internal": {
                "@2,source": {
                  "Facebook": {
                    "#true": "userFlag"
                  },
                  "*": {
                    "@4,internalAccount": "userFlag"
                  }
                }
              },
              "*": {
                "@2,internalAccount": "userFlag"
              }
            }
          }
        }
      }
    ]