'JOLT Tranformation using dynamic key value

I am trying covert the below JSON to a specific format

INPUT

{
  "var_name1" : "alarmID",
  "var_val1" : "12345678",
  "var_name2" : "witscsAlarmTime",
  "var_val2" : "2022-05-10T03:46:38.376Z",
  "var_name3" : "witscsAlarmSeverity",
  "var_val3" : "major",
  "var_name4" : "witscsAlarmBody",
  "var_val4" : "Enterprise Manager was unable to communicate",
  "var_name5" : "witscsAlarmToken"
}

Required Output

{
  "trap_variables" : {
    "alarmID": "12345678", 
    "witscsAlarmTime": "2022-05-10T03:46:38.376Z", 
    "witscsAlarmSeverity": "major", 
    "witscsAlarmBody": "Enterprise Manager was unable to communicate"
  }
}

I am unable to build a JOLT spec which can dynamically change the key of the output. The var_name and var_val s of the input are not restricted to just 4 set of values, the set count can change from request to request.

What should be the JOLT spec to achieve this?



Solution 1:[1]

You can use two successive shift operations through use of * wildcards for each group(var_value(s) and var_name(s)) such as

[
  {
    "operation": "shift",
    "spec": {
      "var_val*": "v[]",
      "var_name*": "n[]"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "v": {
        "*": "trap_variables.@(2,n[&])"
      }
    }
  }
]

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

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1