'Count the total items and items with specific condition in a json using Jolt

The input JSON is :

{
  "subOrderItems": [
    {
      "travellerDetails": {
        "title": "Ms.",
        "name": "XYZ",
        "gender": "F"
      },
      "random_key": "random_key",
      "random_value": "random_value"
    },
    {
      "travellerDetails": {
        "title": "Mr.",
        "nationality": "AU",
        "name": "ABC",
        "gender": "M"
      },
      "random_key": "random_key",
      "random_value": "random_value"
    },
    {
      "travellerDetails": {
        "title": "Mr.",
        "nationality": "UK",
        "name": "PQR",
        "gender": "M"
      },
      "random_key": "random_key",
      "random_value": "random_value"
    }
  ]
}

The json has "SubOrderItems" list which is a list of JSON objects. Firstly i would like to get count of number of elements in that list. Secondly, each json has a fiels called "gender", thus would like to have number of males and number of females count.

Expected Output:

{
  "No.of People": 3,
  "No.of Males": 2,
  "No.of Females": 1
}


Solution 1:[1]

You can create lists through seperating by gender attribute, and then compute their size respectively such as

[
  {
    "operation": "shift",
    "spec": {
      "subOrderItems": {
        "*": {
          "travellerDetails": {
            "gender": {
              "M": {
                "@1": "&1[]",
                "@": "P[]"
              },
              "F": {
                "@1": "&1[]",
                "@": "P[]"
              }
            }
          }
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=size(@(1,&))"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "P": "No\\.of People",
      "M": "No\\.of Males",
      "F": "No\\.of Females"
    }
  }
]

where P is the letter which represents combining all genders under the common list.

the demo on the site http://jolt-demo.appspot.com/

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1