jq可以对json数据进行分片、过滤、映射和转换
安装
#CentOS
yum install jq
#MacOS
brew install jq
提取信息
cat json.txt
[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]
- 格式化展示原文
cat json.txt | jq '.'
[
{
"genre": "deep house"
},
{
"genre": "progressive house"
},
{
"genre": "dubstep"
}
]
- 输出数组中的元素,可以使用[index]
cat json.txt | jq '.[0]'
{
"genre": "deep house"
}
- 输出对象的一个字段
jq '.[0].genre' json.txt
"deep house"
数据转换
- 过滤字段
cat json.txt| jq -c '[.[] | {"name", "age"}]'
[{"name":"tenmao","age":100},{"name":"tencent","age":null}]
- 根据KV的值过滤值
cat json.txt| jq -c 'map(select(.name == "tenmao"))'
[{"genre":"deep house","name":"tenmao","age":100}]
- 增加字段
# 使用map: 映射, 其中.号表示原文, + 表示merge信息
# if then else end是逻辑语句
cat json.txt| jq -c 'map(if .name == "tenmao" then . + {hobby: "baskball"} else . end)'
[{"genre":"deep house","name":"tenmao","age":100,"hobby":"baskball"},{"genre":"progressive house","name":"tencent"}]
网友评论