使用 jq 分组并计数 JSON
Group and count JSON using jq
我正在尝试将以下 JSON 转换成一个 csv,其中包含每个唯一的“名称”和总计数(即:该名称出现的次数)。
当前数据:
[
{
"name": "test"
},
{
"name": "hello"
},
{
"name": "hello"
}
]
理想输出:
[
{
"name": "hello",
"count": 2
},
{
"name": "test",
"count": 1
}
]
我试过 [.[] | group_by (.name)[] ]
但出现以下错误:
jq: error (at :11): Cannot index string with string "name"
JQ玩link:https://jqplay.org/s/fWqNUii1b2
注意,我已经在使用 jq 将初始原始数据格式化为上面的格式。请看JQ玩link这里:https://jqplay.org/s/PwwRYscmBK
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
}
]
group_by(.name)
| map({name: .[0].name, count: length})
[
{
"name": "hello",
"count": 2
},
{
"name": "test",
"count": 1
}
]
Jq▷Play
基于 OP 的 ,使用以下 jq 过滤器计算多个对象中的每个名称,其中 .name
是嵌套的。
map(.labels)
| map({name: .[0].name, count: length})
我正在尝试将以下 JSON 转换成一个 csv,其中包含每个唯一的“名称”和总计数(即:该名称出现的次数)。
当前数据:
[
{
"name": "test"
},
{
"name": "hello"
},
{
"name": "hello"
}
]
理想输出:
[
{
"name": "hello",
"count": 2
},
{
"name": "test",
"count": 1
}
]
我试过 [.[] | group_by (.name)[] ]
但出现以下错误:
jq: error (at :11): Cannot index string with string "name"
JQ玩link:https://jqplay.org/s/fWqNUii1b2
注意,我已经在使用 jq 将初始原始数据格式化为上面的格式。请看JQ玩link这里:https://jqplay.org/s/PwwRYscmBK
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
}
]
group_by(.name)
| map({name: .[0].name, count: length})
[
{
"name": "hello",
"count": 2
},
{
"name": "test",
"count": 1
}
]
Jq▷Play
基于 OP 的 .name
是嵌套的。
map(.labels)
| map({name: .[0].name, count: length})