原文地址:http://blog.chinaunix.net/uid-24774106-id-3830242.html
JSON是前端編程經常用到的格式,對於PHP或者Python,解析JSON都不是什麼大事,尤其是PHP的json_encode和json_decode,乾的相當的漂亮。Linux下也有處理處理JSON的神器:jq。
對於JSON格式而言,jq就像sed/awk/grep這些神器一樣的方便,而也,jq沒有亂七八糟的依賴,只需要一個binary文件jq,就足矣。下面我們看下jq的使用。
1 格式化JSON
- manu@manu:~/code/php/json$ cat json_raw.txt
- {"name":"Google","location":{"street":"1600 Amphitheatre Parkway","city":"Mountain View","state":"California","country":"US"},"employees":[{"name":"Michael","division":"Engineering"},{"name":"Laura","division":"HR"},{"name":"Elise","division":"Marketing"}]}
- cat json_raw.txt | jq .
看到上圖,將一團亂麻的JSON格式化成個更可讀的形式。其實背後另外檢查了JSON的合法性。如果JSON不合法,jq .會報錯。我故意寫個錯誤的JSON:
- manu@manu:~/code/php/json$ cat json_err.txt
- {"name":"Google","location":{"street":"1600 Amphitheatre Parkway","city":"Mountain View","state":"California","country":"US"},"employees":[{"name":"Michael","division":"Engineering"}{"name":"Laura","division":"HR"},{"name":"Elise","division":"Marketing"}]}
- manu@manu:~/code/php/json$ cat json_err.txt
|jq .
- parse error: Expected separator between values at line 1, column 183
如上圖json,jq如何解析JSON,根據key獲取value?
- {
- “key_1”:"value_1",
- “key_2”:"value_2",
- }
- jq '.key'
解析不存在的元素,會返回null
- echo
'{"foo": 42, "bar": "less interesting data"}'
| jq .nofoo
- null
- cat json_raw.txt
| jq '.location.state'
- "California"
- cat json_raw.txt
| jq '.employees[1].name'
- "Laura"
jq還有一些內建函數如 key,has
key是用來獲取JSON中的key元素的:
- cat json_raw.txt
| jq 'keys'
- [
- "employees",
- "location",
- "name"
- ]
- cat json_raw.txt
| jq 'has("name")'
- true
- cat json_raw.txt
| jq 'has("noexisted")'
- false
參考文獻:
1 How to parse JSON string via command line on Linux
2 jq - command-line JSON processor