找到一篇挺不错的文章,其中jq工具挺实用的,所以就收集下,以下来至于
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 .
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
{
“key_1”:"value_1",
“key_2”:"value_2",
}
jq '.key'
echo '{"foo": 42, "bar": "less interesting data"}' | jq .nofoo
null
cat json_raw.txt | jq '.location.state'
"California"
4 JSON parse array
cat json_raw.txt | jq '.employees[1].name'
"Laura"
5 内建函数 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