Using Jsonata I need to transform string into array of objects following this

76 Views Asked by At

I am using Jsonata and I am stuck somewhere in the middle. Basically, I receive from a JSON a property called EMAIL: "[email protected]|2|bb@bb-com|4|" . In this format, using Jsonata I need to transform this into

Tried many solutions, but got mainly 5 objects lol. Would appreciate if I can get some help. Also number of emails is not the same always, so would need something dynamic.

INPUT "[email protected]|2|bb@bb-com|4|"

OUTPUT

[ { "email":[email protected] "score":4 "position":1 }, { "email":[email protected] "score":2 "position":2 } ]

1

There are 1 best solutions below

0
mralex On

There might be multiple ways to solve it, but I would use the reduce function after splitting by "|":

$split($, "|") ~> $reduce(function($accumulator, $item, $index) {(
  $isEmailIndex := $index % 2 = 0;
  $position := $index / 2 - $index % 2 + 1;

  $isEmailIndex and $item
    ? $append($accumulator, { "email": $item, "score": $parts[$index+1], "position": $position })
    : $accumulator;
)}, [])

Check it out on the Stedi Playground: https://stedi.link/EG3UGjw