对于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 .
![](/attachment/201308/1/24774106_1375357640PQ0C.png)
看到上图,将一团乱麻的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'
![](/attachment/201308/1/24774106_13753588214y7s.png)
解析不存在的元素,会返回null
-
echo '{"foo": 42, "bar": "less interesting data"}' | jq .nofoo
- null
cat json_raw.txt | jq '.location.state'
"California"
4 JSON parse array "California"
cat json_raw.txt | jq '.employees[1].name'
"Laura"
5 内建函数"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
相关热门文章
给主人留下些什么吧!~~
评论热议