Search code examples
jsonata

JSONata group by multiple fields and count


Does anyone know how to user jsonata to group by multiple fields and count ? https://docs.jsonata.org/

I can't figure it out, I have been using the jsonata online playground but I can't seem to get anywhere.

I have an array of objects and I want to group by multiple fields and count

I have been doing this earlier in mysql and it is very simple but now when the "records" are json objects I am bit lost and need help

The result should be a new array with the grouped fields + count of the grouped fields

Thanks, Jani


Solution

  • It is a bit hacky solution, but I think it does what you want:

    $${
      API_TYPE & API_VERSION & METHOD_NAME: {
        "API_TYPE": [API_TYPE][0],
        "API_VERSION": [API_VERSION][0],
        "METHOD_NAME": [METHOD_NAME][0],
        "COUNT": $count($)
      }
    } ~> $each(function($value) {$value})
    

    The trick is to use the grouping feature, and group by all three parameters by concatenating them to a single string.

    See it in action: https://stedi.link/L1a9Tiv