Multiple statements with JQ: Cumulate multiple fields

713 views Asked by At

This is my data for this example:

[
  {
    "date": "25-09-20",
    "nbrMembers": 1,
    "nbrWallets": 4
  },
  {
    "date": "26-09-20",
    "nbrMembers": 3,
    "nbrWallets": 1
  },
  {
    "date": "27-09-20",
    "nbrMembers": 0,
    "nbrWallets": 2
  },
  {
    "date": "28-09-20",
    "nbrMembers": 7,
    "nbrWallets": 3
  }
]

I need to transform the json with cumulate fields. This is the expected result:

[
  {
    "date": "25-09-20",
    "nbrMembers": 1,
    "nbrWallets": 4
  },
  {
    "date": "26-09-20",
    "nbrMembers": 4,
    "nbrWallets": 5
  },
  {
    "date": "27-09-20",
    "nbrMembers": 4,
    "nbrWallets": 7
  },
  {
    "date": "28-09-20",
    "nbrMembers": 11,
    "nbrWallets": 10
  }
]

This is what i'm doing to cumulate just one field:

jq 'foreach .[] as $row (0; . + $row.nbrMembers ; . as $x | $row | (.nbrMembers = $x))' test.json

I just don't know how to do this with multiples fields ?

3

There are 3 answers

0
peak On BEST ANSWER

Succinctly:

jq '[ foreach .[] as $row (null;
          .nbrMembers += $row.nbrMembers
        | .nbrWallets += $row.nbrWallets;
        $row + . ) ]
' test.json
0
Andrei Kovrov On

You can use the whole object instead of just a field as the current element in foreach.

jq '[foreach .[] as $row ({nbrMembers: 0, nbrWallets: 0}; {nbrMembers: ($row.nbrMembers + .nbrMembers), nbrWallets:  ($row.nbrWallets + .nbrWallets)  }; . as $x | $row | .nbrMembers = $x.nbrMembers | .nbrWallets = $x.nbrWallets) ]' test.json
4
Andrei Kovrov On

It's a little bit shorter version. We can use $row * . to merge the result)


jq '[foreach .[] as $row (
      {nbrMembers: 0, nbrWallets: 0};
      { 
        nbrMembers: ($row.nbrMembers + .nbrMembers), 
        nbrWallets: ($row.nbrWallets + .nbrWallets)
      }; 
     $row * .  
    )]' test.json