jq按特定键计算json中的项目数

Ele*_*nor 7 bash command-line json count jq

以下是我的json文件中的前两项

{
"ReferringUrl": "N",
"OpenAccess": "0",
"Properties": {
    "ItmId": "1694738780"
   }
}
{
"ReferringUrl": "L",
"OpenAccess": "1",
"Properties": {
    "ItmId": "1347809133"
  }
}
Run Code Online (Sandbox Code Playgroud)

我想计算每个ItmId出现在json中的项目数.例如,带有"ItmId"1694738780的项目出现10次,带有"ItmId"1347809133的项目在我的json文件中出现14次.然后像这样返回一个json

{"ItemId": "1694738780",
 "Count":  10
}
{"ItemId": "1347809133",
 "Count":  14
}
Run Code Online (Sandbox Code Playgroud)

我正在使用bash.并且更喜欢完全由jq完成.但是可以使用其他方法.

谢谢!!!

skr*_*skr 12

使用 jq 命令

cat json.txt | jq '.Properties .ItmId' | sort | uniq -c | awk -F " " '{print "{\"ItmId\":" $2 ",\"count\":" $1"}"}'| jq .
Run Code Online (Sandbox Code Playgroud)


pea*_*eak 10

这是一个解决方案(假设输入是有效JSON对象的流),并使用-s选项调用jq:

map({ItemId: .Properties.ItmId})             # extract the ItmID values
| group_by(.ItemId)                          # group by "ItemId"
| map({ItemId: .[0].ItemId, Count: length})  # store the counts
| .[]                                        # convert to a stream
Run Code Online (Sandbox Code Playgroud)

inputs如果你的jq拥有它,那么将使用更节省内存的方法; 但在这种情况下,使用-n代替-s,并将上面的第一行替换为:[inputs | {ItemId:.Properties.ItmId}]