对于JSON格式而言,jq就像sed/awk/grep这些神器一样的方便,而也,jq没有乱七八糟的依赖,只需要一个binary文件jq,就足矣。
下面我们看下jq的使用
格式化JSON root@silent:~/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"}]}root@silent: cat json_raw.gz | jp .
如果json 格式不正确,使用jq时会报错
root@silent:~/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"}]上面JSON中加粗和斜体部分,遗漏了一个逗号,所以这个JSON是错误的,jq轻松的可以轻松的检查出来:
root@silent:~/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获取value? 可以使用 jq ‘.key’
{ "key_1":"value_1", "key_2":"value_2", }解析不存在的元素,会返回null
echo '{"foo": 42, "bar": "less interesting data"}' | jq .nofoo nulljq 还有一些内建函数如 key,has key 是用来获取JSON中的 key 元素的:
cat json_raw.txt | jq ‘keys’ [ “employees”, “location”, “name” ]
has是用来是判断是否存在某个key:
cat json_raw.txt | jq ‘has(“name”)’ true cat json_raw.txt | jq ‘has(“noexisted”)’ false