Search code examples
jsonjolt

JOLT to check the value if it is null keep it as it is else update the value based on the condition


please provide the jolt spec for the following JSON input :

[
  {
    "name": "Manu",
    "age": 26,
    "location": "New York",
    "risk": "0"
  },
  {
    "name": "Manju",
    "age": 29,
    "location": "New York city",
    "risk": null
  }
]

if risk is 0, then risklevel is Low

if risk is null, then risklevel is null

if risk is 1, then risklevel is High

[
  {
    "name": "Manu",
    "age": 26,
    "location": "New York",
    "risklevel": "Low"
  },
  {
    "name": "Manju",
    "age": 29,
    "location": "New York city",
    "risklevel": null
  }
]

Spec tried is :

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "name": "[&1].name",
        "age": "[&1].age",
        "location": "[&1].location",
        "risk": {
          "0": {
            "#Low": "[&2].risklevel"
          },
          "1": {
            "#High": "[&2].risklevel"
          },
          "null": null,
          "*": {
            "@(2,risklevel)": "[&2].risklevel"
          }
        },
        "*": "[&1].risklevel"
      }
    }
  },
  {
    "operation": "default",
    "spec": {
      "*": {
        "risklevel": "null"
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "risklevel": "=toString"
      }
    }
  }
]

Solution

  • You can use the following transformation :

    [//set an arbtrary value(say "NUll") to a null valued "risk"
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "~risk": "NUll"//occures whnever risk is null due to the ~ operator 
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": "[&1].&", //the attributes other than "risk"
            "risk": {
              "1": { "#High": "[&3].riskLevel" },//hardcode by # operator
              "0": { "#Low": "[&3].riskLevel" },
              "NUll": { "@": "[&3].riskLevel" }
            }
          }
        }
      }
    ]
    
    • Refer for the usage of ~ operator within a modify spec

    the demo on the site https://jolt-demo.appspot.com/ is :

    enter image description here