赞
踩
在liunx上的下载命令:: sudo yum install jq
在macbook上的下载命令:: brew install jq
如下,你有一个json变量:
student='{"name":"John","age":25,"gender":"male","address":{"city":"New York","state":"NY"},"hobbies":["reading","swimming","traveling"]}'
students='[
{ "name": "Alice", "age": 25, "address": { "city": "New York", "state": "NY" } },
{ "name": "Bob", "age": 40, "address": { "city": "San Francisco", "state": "CA" } },
{ "name": "Charlie", "age": 35, "address": { "city": "Seattle", "state": "WA" } },
{ "name": "Jieyuan", "age": 35, "address": { "city": "Seattle", "state": "WA" } }
]'
由于此时不太方便查看,你可以使用 echo $student | jq . 来格式化。
1.将名为student的json变量中拿到他的name字段:
echo $student | jq .name
2.从名为student的json变量中选择"address"对象下的"city"字段,并将其输出到终端:
echo $student | jq '.address.city'
3.从students中选择所有年龄大于30的对象,并输出它们的名称
echo $students | jq '.[] | select(.age > 30) | .name'
1.将数组中的某个属性拿出来并展示出来
echo $students | jq '.[].name'
2.将数组中的每一个元素,仅保留name属性,并将其转换为新的对象格式输出。
echo $students | jq '.[] | { "name" }'
3.通过select 过滤
获取年龄大于30岁的学生;
echo $students | jq '.[] | select(.age<30)'
4.通过map 将age大于25的所有学生获取
echo $students | jq 'map(select(.age >25))'
获取拿出年龄是25 和40的人
echo $students | jq 'map(select(.age | IN (40,25)))'
沿用上面的students
1.将年龄为35,40的人的名字拼接在一起,用分号相隔;
首先,获取到年龄35,40的人的集合::resultData=$( echo $students | jq 'map(select(.age | IN (40,35)))')
其次,获取他们的名字并拼接:: (echo "$resultData" | jq -r '.[].taskId' | tr '
' ';'
⚠️注意上面语句tr后面是刻意的去换行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。