Json

使用 jq 填充 json 數據並列印出現次數

  • March 23, 2022

我試圖用 jq 填充低於 json 數據並期望輸出如下

{
 "data": [
   {
     "topic_name": "BookShow",
     "topic_id": "ABCDFG",
     "urgency": "high"
   },
   {
     "topic_name": "AmzonMarket",
     "topic_id": "ESDCGHY",
     "urgency": "high"
   },
   {
     "topic_name": "AmzonMarket",
     "topic_id": "ESDCGHY",
     "urgency": "high"
   },
   {
     "topic_name": "BookShow",
     "topic_id": "ABCDFG",
     "urgency": "high"
   },
   {
     "topic_name": "bookTick",
     "topic_id": "KOLPUYDD",
     "urgency": "high"
   },
   {
     "topic_name": "bookTick",
     "topic_id": "KOLPUYDD",
     "urgency": "high"
   }
 ],
 "more": false,
 "limitations": 100,
 "range": 0
}

期望輸出如下,這裡的“出現”將是新欄位,它計算出現的次數。

"id","name","occurrences"
"KOLPUYDD","bookTick",2
"ABCDFG","BookShow",2
"ESDCGHY","AmzonMarket",2

請支持。

用於形成按其group_by分組的所需對象topic_id並從中創建 CSV。

jq --raw-output '[ "id", "name", "occurrences" ], ( .data | group_by(.topic_name)[] | 
 { id: .[0].topic_id, name: .[0].topic_name, occurrences: length } | 
   [.id, .name, .occurrences]) | @csv'

jqplay展示

引用自:https://unix.stackexchange.com/questions/696502