Group and count JSON using jq

Viewed 453

I am trying to convert the following JSON into a csv which has each unique "name" and the total count (i.e: number of times that name appears).

Current data:

[
  {
    "name": "test"
  },
  {
    "name": "hello"
  },
  {
    "name": "hello"
  }
]

Ideal output:

[
    {
        "name": "hello",
        "count": 2
    },
    {
        "name": "test",
        "count": 1
    }
]

I've tried [.[] | group_by (.name)[] ] but get the following error:

jq: error (at :11): Cannot index string with string "name"

JQ play link: https://jqplay.org/s/fWqNUii1b2

Note, I am already using jq to format the initial raw data into the format above. Please see the JQ play link here: https://jqplay.org/s/PwwRYscmBK

2 Answers
group_by(.name) 
    | map({name: .[0].name, count: length})   
[
  {
    "name": "hello",
    "count": 2
  },
  {
    "name": "test",
    "count": 1
  }
]

Jq▷Play


Based on OP's comment, use the following jq filter to count each name across multiple objects, where the .name is nested.

map(.labels) 
    | map({name: .[0].name, count: length})

Jq▷Play

echo '[{"name": "test"}, {"name": "hello"}, {"name": "hello"}]' | jq 'group_by (.name)[] | {name: .[0].name, count: length}' | jq -s
[
  {
    "name": "hello",
    "count": 2
  },
  {
    "name": "test",
    "count": 1
  }
]
Related