Csv

如何將此 JSON 轉換為 CSV?

  • August 23, 2021

我有下面的 JSON 文件要轉換為 CSV。我需要在一次迭代的同時用第二和第三(它們可以是字元串或數組)迭代第一列。

範例文件:

[
 {
   "results": [
      [
       "abc025",
       "true",
       "test.lun"
     ],
      [
       "xyz025",
       [
         "true",
         "false",
         "true"
       ],
       [
         "product.lun",
         "app.lun",
         "ora.lun"
       ]
     ]
   ]
 }
]

預期的 CSV:

"abc025","true","test.lun"
"xyz025","true","product.lun"
"xyz025","false","app.lun"
"xyz025","true","ora.lun"

使用jq表達式

.[].results[] | .[0] as $name | .[1:] | map([.[]]? // [.]) |
(.[0]|keys[]) as $i | [ $name, .[][$i] ] | @csv

這裡的第一行從每個單獨的子數組(分別在單獨的迭代中)中挑選出第一個元素 ( ) ,然後$name將每個子數組 ( ) 中的剩餘數據轉換為每列一個數組的數組:.[0]``abc025``xyz025``.[1:]

[["true"],["test.lun"]]
[["true","false","true"],["product.lun","app.lun","ora.lun"]]

這是map()在每個元素被提取為數組的呼叫中完成的。如果這不起作用,則將元素放入數組中。因此,每個元素要麼保留為數組,要麼轉換為單個元素數組。

第二行遍歷這些列數組的索引並將輸出創建為 CSV。

測試:

$ jq -r '.[].results[] | .[0] as $name | .[1:] | map([.[]]? // [.]) | (.[0]|keys[]) as $i | [ $name, .[][$i] ] | @csv' file
"abc025","true","test.lun"
"xyz025","true","product.lun"
"xyz025","false","app.lun"
"xyz025","true","ora.lun"

請注意,這是我對您之前的問題的解決方案的概括。您也可以將此程式碼與來自該問題的數據一起使用。

您也可以在超過三列的數據上使用它。文件

[
 {
   "results": [
     [ "abc025",
       "true",
       "test.lun",
       "blueberry" ],
     [ "xyz025",
       ["true","false","true"],
       ["product.lun","app.lun","ora.lun"],
       ["strawberry","cloudberry","lingonberry"] ]
   ]
 }
]

會轉換成

"abc025","true","test.lun","blueberry"
"xyz025","true","product.lun","strawberry"
"xyz025","false","app.lun","cloudberry"
"xyz025","true","ora.lun","lingonberry"

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