Search code examples
jsonata

count matches using JSONata


I have a payload similar to this:

[
  {
    "_id": {
      "$oid": "yadayadayada"
    },
    "ownership_id": "yadayadayada",
    "execution_id": "yadayadayada",
    "execution_date": {
      "$date": "yadayadayada"
    },
    "event_type": "yadayadayada",
    "value_stream": "yadayadayada",
    "app_name": "yadayadayada",
    "repository": "yadayadayada",
    "project": "yadayadayada",
    "last_error_message": "yadayadayada",
    "s_ack_rate": true,
    "b_doc": true,
    "b_plan": true,
    "b_cover": true,
    "b_alerts": true,
    "b_dashboard": true,
    "b_track": true,
    "b_logging": true,
    "b_mark": true,
    "b_test": true,
    "b_check": true
  },
  {
    "_id": {
      "$oid": "yadayadayada"
    },
    "ownership_id": "yadayadayada",
    "execution_id": "yadayadayada",
    "execution_date": {
      "$date": "yadayadayada"
    },
    "event_type": "yadayadayada",
    "value_stream": "yadayadayada",
    "app_name": "yadayadayada",
    "repository": "yadayadayada",
    "project": "yadayadayada",
    "last_error_message": "yadayadayada",
    "s_ack_rate": false,
    "b_doc": true,
    "b_plan": true,
    "b_cover": true,
    "b_alerts": true,
    "b_dashboard": true,
    "b_track": true,
    "b_logging": true,
    "b_mark": true,
    "b_test": true,
    "b_check": true
  }
]

and I was looking for a way to find if some fields are defined as true, for example (b_plan, b_cover, b_dashboard) and count how many element in the array matches this creteria using JSONata.

I tried to create an expression like this: $count(($[b_plan = true] ; $[b_cover = true] ; $[b_dashboard = true]))

but it also returns fields defined as false and null.

I also tried to create an expression with and: $count(($[b_plan = true] and $[b_cover = true] and $[b_dashboard = true]))

but it returned 1 because a saw that expressions with and only returns true or false.


Solution

  • Combine the conditions in a single predicate:

    $count($[b_plan = true and b_cover = true and b_dashboard = true])

    See https://try.jsonata.org/AbOg_KEfL