如果您经常从命令行或shell脚本处理JSON格式的文本,你一定特别希望有一个Linux命令行下的JSON解析工具。
在本文中,将介绍一下Linux命令行下的JSON字符串的解析工具
jq
。
1、安装jq
:
CentOS 系统的epel源提供了该软件包,可以直接使用yum
安装:
$ yum -y install jq
2、JSON示例:
$ cat json.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" } ] }
3、jq
示例:
## 1. 格式化JSON: $ cat json.txt | jq . { "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" } ] } ## 2. 解析JSON对象: $ cat json.txt | jq '.name' "Google" ## 3. 解析嵌套的JSON对象: $ cat json.txt | jq '.location.city' "Mountain View" ## 4. 解析JSON数组: $ cat json.txt | jq '.employees[0].name' "Michael" ## 5. 从一个JSON对象中提取特定字段: $ cat json.txt | jq '.location | {street, city}' { "city": "Mountain View", "street": "1600 Amphitheatre Parkway" } ## 6. JSON对象的过滤: $ cat json.txt | jq '.employees|.[]|select(.name=="Elise")' { "division": "Marketing", "name": "Elise" } ## 7.JSON对象的多重过滤: $ cat json.txt | jq '.employees|.[]|select(.name=="Elise")|.division' "Marketing"
暂无评论