JQ - 根据变量过滤器获取某个键下的特定值
因此,对于课程,我必须制作一个 shell 脚本 (BASH),使用 JQ 来显示超级英雄的秘密身份和力量。这是一门非常有趣的课程。
该脚本将英雄名称打印给用户,然后用户指定他们想要查看哪些英雄的详细信息。
这是我收到的 json 文件的一小部分。
{
"squadName": "Super hero squad",
"homeTown": "Metropolia",
"formed": 2013,
"secretBase": "Super HQ",
"active": true,
"members": [
{
"name": "Atom Man",
"age": 25,
"secretIdentity": "Dan Smith",
"powers": [
"Radiation resistance",
"Radiation blast"
]
}
]
}
因此,如果用户输入“Atom Man”,脚本应该打印他的秘密身份 ("secretIdentity": "Dan Smith")
和他的权力。
("powers": [
"Radiation resistance",
"Radiation blast"
])
这是部分完成的脚本。
#!/bin/bash
while [ true ]
do
cat superhero.json | jq -r '.mem [] | .name' #display the hero names for user.
read -p "Which heroes details do you want to see? Enter 'exit' to quit. :" HERONAME1
if [ "$HERONAME1" = "exit" ]
then
echo "Quitting..."
exit
else
cat superhero.json | jq -r '.member [] | .name [] '
#or jq '.members[].name' superhero.json'
fi
done
现在我陷入了脚本的这一部分。
else
cat superhero.json | jq -r '.member [] | .name [] '
我不太明白如何使用 HERONAME1 变量从 json 文件中过滤某个英雄,以及如何在输出中包含他们的能力。
任何和所有的指针都受到高度赞赏!
So for class I have to make an shell script (BASH) that uses JQ to display a superheroes secret identity and powers. It has been a pretty fun course.
The script prints the hero names to the user, who then specifies which heroes details they want to see.
Here is a small part of the json file that I have been given.
{
"squadName": "Super hero squad",
"homeTown": "Metropolia",
"formed": 2013,
"secretBase": "Super HQ",
"active": true,
"members": [
{
"name": "Atom Man",
"age": 25,
"secretIdentity": "Dan Smith",
"powers": [
"Radiation resistance",
"Radiation blast"
]
}
]
}
So if the user enters "Atom Man", the script should print his secret identity ("secretIdentity": "Dan Smith")
and his powers.
("powers": [
"Radiation resistance",
"Radiation blast"
])
And here is the partially done script.
#!/bin/bash
while [ true ]
do
cat superhero.json | jq -r '.mem [] | .name' #display the hero names for user.
read -p "Which heroes details do you want to see? Enter 'exit' to quit. :" HERONAME1
if [ "$HERONAME1" = "exit" ]
then
echo "Quitting..."
exit
else
cat superhero.json | jq -r '.member [] | .name [] '
#or jq '.members[].name' superhero.json'
fi
done
Now I am stuck at this part of my script.
else
cat superhero.json | jq -r '.member [] | .name [] '
I don't quite understand how I can filter a certain hero from the json file using the HERONAME1 variable and how to include their powers in the output as well.
Any and all pointers are highly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我对此的看法。
假设我们有这样的
superhero.json
:这是我的
run.sh
脚本:这是我运行此脚本时的输出:
尝试该脚本。 ;)
Here's my take on this.
Say we have
superhero.json
like this:And here's my
run.sh
script:Here's output when I run this script:
Try the script. ;)