Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group and count JSON using jq [duplicate]

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

like image 556
Vanita Avatar asked Dec 01 '25 20:12

Vanita


1 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

like image 140
0stone0 Avatar answered Dec 03 '25 13:12

0stone0