jsonapache-nifijolt

Adding a Conditional statement in a JOLT


I have a JOLT where I convert temperature values into Celsius. I using this in a NIFI flow and I get different JSON inputs with different values. My JOLT work fine when there's a temperature field in the input JSON but when there's no temperature field in Input JSON my JOLT generates an additional temperature column. I need my JOLT to convert the temperature into Celsius only when there's a temperature field in the input JSON.

Input JSON

[
  {
    "rx_state": 0,
    "tx_id": 3,
    "temp_1": 54.8,
    "trans_battery_flag": 0,
    "ts": 1729646742,
    "station_name": "abc"
  }
]

JOLT Expression

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "Temp_Cel": "=doubleSum(@(1,temp_1),-32)",
        "temp_1": "=divideAndRound(2,@(1,Temp_Cel),1.8)"
      }
    }
  },
  {
    "operation": "remove",
    "spec": {
      "*": {
        "Temp_Cel": ""
      }
    }
  }
]

I need my JOLT to convert temperature only when 'temp_1' field is present in the JSON. For example following JSON should not give me an extra temperature field after JOLT

[
  {
    "bar_absolute": 30.206,
    "tz_offset": 3600,
    "bar_sea_level": 30.483,
    "bar_offset": -0.001,
    "bar_trend": 0.016,
    "ts": 1729646742,
    "station_name": "abc"
  }
]


Solution

  • You can handle the existence issue by suffixing the attribute with a ? operator such as

    "temp_1?": "=divideAndRound(2,@(1,Temp_Cel),1.8)"
    

    eg. just replace "temp_1" with "temp_1?" within the first spec