jq - 一个灵活轻量的命令行JSON处理器
安装
# Mac 安装 jq 指令
$ brew install jq
示例
# 原始数据
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀
{"result":[["美图秀秀vip","3193.8094555873927"]]}%
# json 格式化 pretty .
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀 | jq .
{
"result": [
[
"美图秀秀vip",
"4020.6379542395694"
]
]
}
# json 压缩输出 -c
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀 | jq -c
{"result":[["美图秀秀vip","4020.6379542395694"]]}
# 解析数据 .result[][0]
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀 | jq '.result[][0]'
"美图秀秀vip"
# 遍历打印数组 .[]
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'|jq '.[]' -c
{"name":"lee","age":12}
{"name":"han","age":21}
{"name":"tom","age":50}
# | 通过管道将一个过滤器的输出当做下一个过滤器的输入
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]' | jq '.[] | .name'
"lee"
"han"
"tom"
# 按条件筛选 map(select(.age>20))
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]' | jq 'map(select(.age>20))' -c
[{"name":"han","age":21},{"name":"tom","age":50}]
类似指令
node 命令行 json 处理器 官方文档
# 安装 nodejs 模块 json
$ npm install -g json
# 原始数据
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀
{"result":[["美图秀秀vip","3193.8094555873927"]]}
# 格式化 json
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀 | json
{
"result": [
[
"美图秀秀vip",
"3193.8094555873927"
]
]
}
# 解析数据
$ curl -s https://suggest.taobao.com/sug\?code\=utf-8\&q\=美图秀秀 | json result | json -a 0
美图秀秀vip
# 遍历数组 -a
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'| json -a
{
"name": "lee",
"age": 12
}
{
"name": "han",
"age": 21
}
{
"name": "tom",
"age": 50
}
# 压缩输出
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'|json -o jsony-0
[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]
# 按条件筛选 -c 'this.age > 20'
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'| json -c 'this.age > 20'
[
{
"name": "han",
"age": 21
},
{
"name": "tom",
"age": 50
}
]
# 写入文件
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]' > sample.json
# 读取文件 -f
$ json -f sample.json -a 0 name age
lee 12
han 21
tom 50
# 编辑
$ json -f sample.json -e 'this.gender=1'
[
{
"name": "lee",
"age": 12,
"gender": 1
},
{
"name": "han",
"age": 21,
"gender": 1
},
{
"name": "tom",
"age": 50,
"gender": 1
}
]
# 取第一个
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'|json 1 -o jsony-0
{"name":"han","age":21}
# 取最后一个
$ echo '[{"name":"lee","age":12},{"name":"han","age":21},{"name":"tom","age":50}]'|json -- -1
{
"name": "tom",
"age": 50
}
作者:Plucky
出处:https://www.1991.wiki/topics/2
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可,如您转载必须以链接形式注明原文地址。
满招损,谦受益。