[英]command output give object string how to convert it to json using jq
一個命令給出了以下輸出,它排列在一個對象中,如何使用 jq 將其轉換為 json?
{\n currentBlock: 4769045,\n highestBlock: 7063981,\n knownStates: 15306625,\n pulledStates: 15306625,\n startingBlock: 0\n}
注意輸出不是json; 它包含\\n
字符串。
我使用以下內容來轉換它
echo "$output" | jq -R -s -c 'split("\n")'
但輸出並不像我預期的那樣
["{","currentBlock:4787477,","highestBlock:7063981,","knownStates:15306625,","pullStates:15306625,","startingBlock:0","}",""]
如果這里的問題是准 JSON 包含文字 "\\n" 字符串,那么您也許可以使用sed 's/\\\\n//g'
刪除它們:
$ output='{\n currentBlock: 4769045,\n highestBlock: 7063981,\n knownStates: 15306625,\n pulledStates: 15306625,\n startingBlock: 0\n}'
$ jq -n -f <(sed 's/\\n//g' <<< "$output")
另一種可能性可能是使用printf
,例如
$ printf "$output" "" | hjson -j
兩者都產生有效的 JSON。
在這種特殊情況下,最初顯示的“輸出”是一個有效的 jq 程序,因此要將其轉換為 JSON,您只需將其作為程序提供給 jq 處理器,例如:
jq -n '{ currentBlock: 4479441, highestBlock: 7063981, knownStates: 15306625, pulledStates: 15306625, startingBlock: 0 }'
{
"currentBlock": 4479441,
"highestBlock": 7063981,
"knownStates": 15306625,
"pulledStates": 15306625,
"startingBlock": 0
}
如果准 JSON 在一個文件中,比如 data.txt,那么你可以簡單地運行:
jq -n -f data.txt
這種方法僅在文本恰好作為 jq 程序有效時才有效。 特別是,如果任何鍵是未加引號的 jq 關鍵字,或者與正則表達式不匹配,則它將不起作用:
^[A-Za-z_][A-Za-z0-9_]*$
一個通用的解決方案是使用諸如hjson 之類的工具:
$ echo '{ currentBlock: 4479441, highestBlock: 7063981, knownStates: 15306625, pulledStates: 15306625, startingBlock: 0 }' |
hjson -j
{
"currentBlock": 4479441,
"highestBlock": 7063981,
"knownStates": 15306625,
"pulledStates": 15306625,
"startingBlock": 0
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.