使用 jq 分析 JSON
linux json -echo "[1,2,3]" | jq .
Why
有時候面對一團 JSON 卻不想寫程式,這時候就能拿 jq 出來用。
What
Install
sudo apt install jq
format
讓 JSON 排列的更整齊
input:
echo '{ "name": "a", "value": "b", "desc": "c" }' | jq .
output:
{
  "name": "a",
  "value": "b",
  "desc": "c"
}
pick
挑出陣列中每個物件中鍵值為 name 和 value 的值
input: [{ "name": "a", "value": "b", "desc": "c" }, { "name": "d", "value": "e", "desc": "f" }]
jq '.[] | {"name", "value"}'
output: { "name": "a", "value": "b" } {"name": "d", "value": "e" }
要讓輸出更像 JSON 你可以用 [] 將他包起來。
input: [{ "name": "a", "value": "b", "desc": "c" }, { "name": "d", "value": "e", "desc": "f" }]
`jq '[.[] | {"name", "value"}]'`
output: [{ "name": "a", "value": "b" },{"name": "d", "value": "e" }]
filters
過濾出符合條件的項目
input:	[{"id": 1, "val": 1}, {"id": 2, "val": 2}]
jq '.[] | select(.id == 1)'
output:	{ "id": 1, "val": 1 }
array 長度
input:	[{"id": 1, "val": 1}, {"id": 2, "val": 2}]
jq '. | length'
output: 2
還有更多技巧,但這應該已經夠用了。
    
    >>
     從圖像中掃描解碼條碼