簡體   English   中英

將bash數組轉換為json數組並使用jq插入到文件中

[英]Convert bash array to json array and insert to file using jq

給定一個bash數組,如何將其轉換為JSON數組以便輸出到帶有jq的文件?

另外:有沒有辦法保持server_nohup數組不變,而不是每次都重寫整個json文件?

newArray=(100 200 300)
jq -n --arg newArray $newArray '{
    client_nohup: [ 
        $newArray
    ],
    server_nohup: [

    ]
}' > $projectDir/.watch.json

當前輸出:

{
"client_nohup": [
    "100"
],
"server_nohup": []
}

期望的輸出:

{
"client_nohup": [
    100,
    200,
    300
],
"server_nohup": []
}

(1)如果newArray中的所有值都作為沒有空格的JSON值有效,那么您可以將值作為流輸出,例如

newArray=(100 200 300)
echo "${newArray[@]}" |
  jq -s '{client_nohup: ., server_nohup: []}'

(2)現在讓我們假設您只想更新文件中的“nohup”對象,比如nohup.json:

{ "client_nohup": [], "server_nohup": [ "keep me" ] }

既然你正在使用bash,那么你可以寫:

echo "${newArray[@]}" |
  jq -s --argjson nohup "$(cat nohup.json)" '
    . as $newArray | $nohup | .client_nohup = $newArray
  '

產量

(1)

{
  "client_nohup": [
    100,
    200,
    300
   ],
  "server_nohup": []
}

(2)

{
  "client_nohup": [
    100,
    200,
    300
  ],
  "server_nohup": [
    "keep me"
  ]
}

其他情況

哪里有遺囑,有jq方式:-)

例如,參見如何將bash數組格式化為JSON數組的接受答案(盡管這不是一個完全通用的解決方案)。

有關通用解決方案,請參閱𝑸: How can a variable number of arguments be passed to jq? How can a bash array of values be passed in to jq as a single argument? 𝑸: How can a variable number of arguments be passed to jq? How can a bash array of values be passed in to jq as a single argument? 在jq常見問題解答https://github.com/stedolan/jq/wiki/FAQ

通用解決方案

要清楚,如果已知數組值是有效的JSON,那么有幾個不錯的選擇; 如果數組值是任意的bash字符串,那么用jq處理它們的唯一有效,通用的方法是使用-R jq選項(例如與-s一起使用),但是(bash)字符串將全部被讀入作為JSON字符串,因此任何預期的類型信息都將丟失。 (這里的要點取決於bash字符串不能包含NUL字符的技術性。)

通常,為了減輕后者的顧慮,可以將數字字符串轉換為JSON數字,例如使用jq idiom :( (tonumber? // .)

通常,唯一真正安全的方法是使用jq多次調用,將每個元素添加到上一個命令的輸出中。

arr='[]'  # Empty JSON array
for x in "${newArray[@]}"; do
  arr=$(jq -n --arg x "$x" --argjson arr "$arr" '$arr + [$x]')
done

這可確保在將bash數組的每個元素x添加到JSON數組之前對其進行正確編碼。

然而,這很復雜,因為bash不區分數字和字符串。 這會將您的數組編碼為["100", "200", "300"] ,而不是[100, 200, 300] 最后,您需要了解數組包含的內容,並相應地對其進行預處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM