jq : Linux下json的命令行工具

新建一个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”}]}

1 格式化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 .

输出

jq : Linux下json的命令行工具

 

 2 JSON parse

输入命令:cat json_raw.txt | jq ‘.location’

输出如下:

{
“street”: “1600 Amphitheatre Parkway”,
“city”: “Mountain View”,
“state”: “California”,
“country”: “US”
}

 

3 JSON nested parse(嵌套解析)  

输入命令:cat json_raw.txt | jq ‘.location.state’

输出如下:

“California”

4 JSON parse array   

输入命令:cat json_raw.txt | jq ‘.employees[1].name’

输出如下:

“Laura”

 5 内建函数

输入命令:cat json_raw.txt | jq ‘keys’

输出如下:

[

“employees”,

“location”,

“name”

]

 

has是用来是判断是否存在某个key:

输入命令:cat json_raw.txt | jq ‘has(“name”)’

输出如下:

true

6.jq的管道操作

输入命令:cat json_raw.txt | jq ‘.employees[]|{name}’

输出如下:

{
“name”: “Michael”
}
{
“name”: “Laura”
}
{
“name”: “Elise”
}