简体   繁体   English

使用 jq 从 json 文件中提取信息

[英]extract information from a json file with jq

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:如果植物的名称是 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

but nothing is printed out.但没有打印出来。 I should get Category-1.我应该得到 Category-1。 Any ideas please?有什么想法吗?

You were almost there:你几乎在那里:

jq -C 'select(.Plants[] | (.Name == "corn-1" and .Price == "20")).Id'

The problem was you used .Price in the context of the top object, so it never matched.问题是您在顶部.Price的上下文中使用了 .Price,所以它永远不会匹配。

If there are several matches in one Plants, the Id will be printed multiple times.如果一个 Plants 中有多个匹配项,则 Id 将被打印多次。 To get it only once, you can use要只获得一次,您可以使用

jq -C 'select(.Plants | any(.Name == "corn-1" and .Price == "20")).Id'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM