Json
將文本更改為 JSON
輸入數據範例(
^
- 分隔欄位):C-11^Mark^Docking AWS C-12^Mark^Docking AWS C-13^Lay^Ploting C-14^Lay^Ploting C-15^Lay^Ploting C-16^Vincent^GPU Calc C-17^Vincent^GPU Calc C-18^Vincent^GPU Calc C-19^Vincent^GPU Calc
我使用這個命令:
jq -Rn ' [inputs | select(. != "") / "^"] | reduce .[] as [$container, $user, $job] ({}; .[$job] += [{$user, $container}] ) 'test.csv > test.json
我正確地得到以下 JSON 輸出:
"Docking AWS\r": [ { "user": "Mark", "container": "C-11" }, { "user": "Mark", "container": "C-12" } ],
…但我希望它的格式類似於以下 JSON:
Docking AWS user: Mark container: C-11,C-12 "Docking AWS\r": [ { "user": "Mark", "container": "C-11","C12" },
我怎樣才能做到這一點?
++編輯++
{ "job": "Docking AWS", "user": "Mark", "container": [ "C-11", "C-12" ] }
我想要這種格式如何轉換?
我假設您想要以下結果:
{ "Docking AWS": { "user": "Mark", "container": [ "C-11", "C-12" ] }, "Ploting": { "user": "Lay", "container": [ "C-13", "C-14", "C-15" ] }, "GPU Calc": { "user": "Vincent", "container": [ "C-16", "C-17", "C-18", "C-19" ] } }
這可以通過使用
reduce
從原始行的拆分子字元串建構結果結構來實現:jq -Rn ' reduce ( inputs / "^" ) as [$container,$user,$job] ({}; .[$job] |= ( .user |= $user | .container += [ $container ] ) )' file
這用於
reduce
讀取輸入並將其拆分為每個包含三個元素的短數組。從空對像開始,通過更新子對象添加新鍵。鍵引用的子對象通過將$job
鍵設置user
為$user
並添加$container
到對像中的數組來更新container
。這與您的程式碼之間的主要區別在於,我正在更新結果中的對象,而不僅僅是為每個輸入行添加它們。我也將
.[$job].container
其視為一個數組。由於您似乎正在使用 DOS 文本文件,您可能希望使用 將輸入數據轉換為 Unix 文本文件
dos2unix
,或者使用手動從每行末尾刪除輸入符jq
(更改inputs / "^"
為inputs | rtrimstr("\r") / "^"
)。修改後的問題,我解釋它的方式,要求創建一個頂級作業數組,而不是將每個作業作為頂級對像中的鍵。這是一個
reduce
稍微調整呼叫以包含一個job
將字元串作為值的鍵,$job
然後將reduce
創建的對象放入數組中的問題:jq -Rn ' reduce ( inputs / "^" ) as [$container,$user,$job] ({}; .[$job] |= ( .job |= $job | .user |= $user | .container += [ $container ] ) ) | [ .[] ]' file
鑑於問題中的數據,這將產生
[ { "job": "Docking AWS", "user": "Mark", "container": [ "C-11", "C-12" ] }, { "job": "Ploting", "user": "Lay", "container": [ "C-13", "C-14", "C-15" ] }, { "job": "GPU Calc", "user": "Vincent", "container": [ "C-16", "C-17", "C-18", "C-19" ] } ]