skip to Main Content

I’d like to get the count of elements in an json array using jq (without the elements with "name": "current" in the snapshots array).

{
  "name": "test1",
  "snapshots": [
    {
      "description": "You are here!",
      "name": "current",
      "digest": "ccc",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap1",
      "digest": "ddd",
      "running": 1
    }
  ]
}
{
  "name": "test2",
  "snapshots": [
    {
      "digest": "bbb",
      "description": "You are here!",
      "name": "current",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap1",
      "digest": "aaa",
      "running": 1
    },
    {
      "description": "You are here!",
      "name": "snap2",
      "digest": "abc",
      "running": 1
    }
  ]
}

This is the result I’m looking for (excluding the entries with "name: "current" in the snapshots array):

test1: 1
test2: 2

3

Answers


  1. One way would be to combine string interpolation by writing the filter inside the ".."

    jq --raw-output 
      '"(.name): ( .snapshots | map(select(.name != "current")) | length )"'
    

    demo – jqplay

    Login or Signup to reply.
  2. You may find it useful to define a count function and use that. Using reduce can make it a little quicker too for larger inputs.

    def count(f): reduce (.[] | f) as $i (0; if $i then . + 1 end);
    "(.name): (.snapshots | count(.name != "current"))"
    
    Login or Signup to reply.
  3. … or use the generic stream-oriented count/1 function:

    def count(s): reduce s as $_ (0; .+1);
    
    "(.name): (count(.snapshots[] | select(.name != "current")))"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search