使用 jq 从 json 文件中提取信息
我试图获取 Id:如果植物名称是 corn-1 并且价格是 20,则打印 Id
{
"Id": "Category-1",
"Plants":
[
{
"Name": "corn-1",
"Price": "20"
},
{
"Name": "corn-2",
"Price": "10"
},
{
"Name": "corn-3",
"Price": "5"
},
]
}
cat plants.json | jq -C 'select(.Plants[].Name=="corn-1" and .Price=="20").Id
但没有打印任何内容。我应该获得类别 1。 有什么想法吗?
I tried to get the Id: if the name of the plant is corn-1 and the price is 20 then print the Id
{
"Id": "Category-1",
"Plants":
[
{
"Name": "corn-1",
"Price": "20"
},
{
"Name": "corn-2",
"Price": "10"
},
{
"Name": "corn-3",
"Price": "5"
},
]
}
cat plants.json | jq -C 'select(.Plants[].Name=="corn-1" and .Price=="20").Id
but nothing is printed out. I should get Category-1.
Any ideas please ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你就快到了:
问题是你在顶部对象的上下文中使用了
.Price
,所以它永远不会匹配。如果一个 Plant 中有多个匹配项,则 Id 将被打印多次。要只获取一次,您可以使用
You were almost there:
The problem was you used
.Price
in the context of the top object, so it never matched.If there are several matches in one Plants, the Id will be printed multiple times. To get it only once, you can use