jsonjqinner-product

jq sum and multiply values to get an aggregate


Given the following JSON, is there a way to get the aggregated memory (sum of all memory values multiplied by the number of instances in each case) with a jq query?

{
  "apps": [
    {
      "memory": 512,
      "instances": 3
    },
    {
      "memory": 256,
      "instances": 1
    },
    {
      "memory": 128,
      "instances": 6
    },
    {
      "memory": 1024,
      "instances": 2
    }
  ]
}

In this example it should perform the following operation:

512*3 + 256*1 + 128*6 + 1024*2

so it should give me 4608 in total.

Just for the record, I am using command line jq in CentOS8:

jq --version
jq-1.5

Solution

  • A one-liner solution:

    reduce .apps[] as $x (0; . + ($x | .memory * .instances))
    

    Or more elegantly:

    def sigma(s): reduce s as $x (0; . + $x);
    
    sigma(.apps[] | .memory * .instances)