skip to Main Content

JSONata is honestly driving me crazy. I asked something similar a couple of weeks ago, but I still don’t know what I’m doing so here I am again.

What I’m working with:

[[  {
    "time": "2024-04-26",
    "value": 40
  },
  {
    "time": "2024-04-27",
    "value": 10
  },
  {
    "time": "2024-04-28",
    "value": 20
  }
],
[  {
    "time": "2024-04-26",
    "value_2": 5
  },
  {
    "time": "2024-04-27",
    "value_2": 2
  },
  {
    "time": "2024-04-28",
    "value_2": 4
  }
]]

What I want is to get the distinct values for time and devide the values – value/value_2:

[  {
    "time": "2024-04-26",
    "value": 8
  },
  {
    "time": "2024-04-27",
    "value": 5
  },
  {
    "time": "2024-04-28",
    "value": 5
  }
]

I tried something like this but I only get the distinct values for time.

$type($) = 'array' ? 
(($count($) ) > 0 ? 
$map($[0], function($v, $i, $a) 
{ { "time": $v.time, 
"value": $v.value/ $v.value_2 } })[]: []): undefined 

Output:

[
  {
    "time": "2024-04-26"
  },
  {
    "time": "2024-04-27"
  },
  {
    "time": "2024-04-28"
  }
]

2

Answers


  1. This is ugly but it works

    (
         $obj := $;
    
         $distinct(time) 
         ~> $map(function($v, $i, $a) {
         {$v: {"value": $[time = $v].(value), "value_2": $[time = $v].(value_2)}}
         }) 
         ~> $map(function($v, $i, $a) { $v.*.(value/value_2) })
    

    )

    https://try.jsonata.org/8cTvSB0Ai

    Login or Signup to reply.
  2. How about this:

    (
      /* convert the array to an map of date to value */
      $first := $[0].{time: value};
      $second := $[1].{time: value_2};
    
      /* iterate over the keys, lookup the values
      $keys($first).{
          "time": $,
          "value": $lookup($first, $) / $lookup($second, $)
      }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search