Home > Software engineering >  conditional JSON transformation in JOLT
conditional JSON transformation in JOLT

Time:03-03

I am working with a searching service that accepts as one of the payload attributes distance in kilometers. I.e.

{
  ...
  "distance": "12.8",
  ...
}

However, request I am receiving can include distance either in kilometers or in miles.

{
  ...
  "distance": "22.32",
  "distanceUnit": "mi"
}

Distance unit can be one of "km", "Km", "KM", "mi", "m", "Mi", "MI".

So, if distance unit is something of the first three, I need just to pass through distance to the service. Otherwise, I need to convert it to double, multiply its value by 1.609 and convert it back to string.

I am experienced Java and WS developer but an absolute novice to JOLT and couldn't find anything similar on the web.

With the response I do need to perform conversion back to original units. If someone can help me, I'll appreciate it greatly.

CodePudding user response:

The Jolt doesn't have a function such as multiply or product, but divide and divideAndRound to be used in a modify transformation spec. Then, we'll have a conditional to filer out whether the provided value for distanceUnit attribute exists within the list(mi,m,Mi,MI) or not such as

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "distanceinMiles_": "=divideAndRound(7,@(1,distance),0.6215040397762585)",
      "distanceinMiles": "=toString(@(1,distanceinMiles_))"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "distanceUnit": {
        "mi|m|Mi|MI": { "@(2,distanceinMiles)": "distance" },
        "*": { "@(2,distance)": "distance" }
      }
    }
  }
]

the demo on the site enter image description here

  • Related