'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":  "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 ?



Solution 1:[1]

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.

If there are several matches in one Plants, the Id will be printed multiple times. To get it only once, you can use

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1