jq

Select object from list where value is elsewhere in the JSON


Let's say I have a bit of JSON that looks like this

{
    "fish": [
        {
            "name": "pike",
            "version": 1
        },
        {
            "name": "haddock",
            "version": 2
        }
    ],
    "current_fish_version": 2
}

And I wanted to get the name of the fish with the version equal to current_fish_version.

How would I go about doing that?


Solution

  • Making content from an outer context available is an ideal use case for jq's variable references: X as $name | ... defines $name as available to refer to within ... on the right.

    .current_fish_version as $version
    | .fish[]
    | select(.version == $version)
    | .name