Text-Processing

使用 JQ 將 JSON 導出為帶有標題的 CSV

  • November 19, 2019

我有一個(字典?)JSON 文件,類似於:

{
 "Salad": {
   "name": "Dressing",
   "good": true,
   "status": true
 },
 "Data_XML": {
   "name": "XML",
   "good": false
 },
 "Functionality": {
   "name": "FUNC",
   "good": true
 },
 "Data_JSON": {
   "name": "JSON",
   "good": true,
   "status": false
 }
}

我正在尋找這樣的 CSV 輸出:

"title","good","name","status"
"Salad",true,"Dressing",true
"Data_XML",false,"XML",""
"Functionality",true,"FUNC",""
"Data_JSON",true,"JSON",false

到目前為止我發現和使用的是這個……

jq -r '(map(keys_unsorted) | add | unique) as $cols | $cols, map(. as $row | $cols | map($row[.]))[] | @csv'

輸出:

"good","name","status"
true,"Dressing",true
false,"XML",
true,"FUNC",
true,"JSON",false

我需要沙拉、Data_XML、功能和 Data_JSON的等價物作為第一列(未排序)以及相關數據。

至於***“good”、“name”、“status”,這些將是 Header 欄位,因此需要動態檢索,因為它們是隨機的(每個數據集可能有 4 個,其他數據集多達 10 個)。這是一個相對較大的文件,很難手動解析這些文件,將“標題”作為第一個列標題項。“title”,“good”,“name”,“status”,“something”,“else”,“random”,“etc”***

我覺得我很親近……非常感謝任何幫助!

我認為這會起作用:

jq  -r '["title","name","good","status"],(to_entries|.[]|  
       [.key,.value.good,.value.name,
         (if .value.status == null then "" else .value.status end )]
       )|@csv'

新版本更通用

jq -r ' to_entries as $row | 
 ( ( map(keys_unsorted ) | add | unique ) as $cols |
   ( ["title" , $cols] | flatten) , 
 ( $row | .[] as $onerow | $onerow | 
      ( [ .key , ( $cols |   
          map ($onerow.value[.] as $v | if $v == null then "" else $v end )  ) ] 
        | flatten ) ) ) | @csv '

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