jsontelegrafjsonata

JSON transformation with JSONata


I am very new to JSONata, so I'm sorry if this is a very simple question or an impossible one. I'd like to make the transformation from:

{
  "data":{
       "code1_value": 1,
       "code1_target": 2,
       "code2":3
   }
}

to

{
  "data":{
    "code1":{
          "value":1,
          "target":2
         }
     },
    "code2":3
}

The final goal is to include the transformation in the outputs plugin in Telegraf configuration file, for any key following that format code_tag. I tried several functions but none of them seems to work. Do you have any idea how to do it? Thank you!


Solution

  • There are probably easier ways to achieve that, but I was able to solve it using an ugly $reduce call:

    {
      "data": $each(data, function($value, $key) {{
        "key": $key,
        "value": $value
      }}) ~> $reduce(function($acc, $entry) {(
        $contains($entry.key, "_")
          ? (
            $outerLevelKey := $split($entry.key, "_")[0];
            $innerLevelKey := $split($entry.key, "_")[1];
            
            $merge([$acc, { 
              $outerLevelKey: $merge([
                $lookup($acc, $outerLevelKey), 
                { $innerLevelKey: $entry.value }
              ])
            }])
          )
          : $merge([$acc, { $entry.key: $entry.value }])
      )}, {})
    }
    

    You can test it on the Stedi Playground