Trying to learn how to think in jq script.
Given this data:
{
"characters": [
{ "First": "Fred", "Last": "Weasley" },
{ "First": "George", "Last": "Weasley" },
{ "First": "Hermione", "Last": "Granger" },
{ "First": "Ron", "Last": "Weasley" },
{ "First": "Hagrid" },
{ "First": "Draco", "Last": "Malfoy" },
{ "First": "Molly", "Last": "Weasley" },
{ "First": "Voldemort" },
{ "First": "Lucius", "Last": "Malfoy" }
]
}
Find all characters with the same last name as "Ron". And no, you don’t already know his last name.
>Solution :
Find the last name you are looking for and save it in a variable, then update the characters array accordingly:
jq '
(.characters[] | select(.First == "Ron").Last) as $last
| .characters |= map(select(.Last == $last))
'
{
"characters": [
{
"First": "Fred",
"Last": "Weasley"
},
{
"First": "George",
"Last": "Weasley"
},
{
"First": "Ron",
"Last": "Weasley"
},
{
"First": "Molly",
"Last": "Weasley"
}
]
}
If you want to make the call with a dynamic first name, provide it using a parameter variable:
jq --arg first "Ron" '
(.characters[] | select(.First == $first).Last) as $last
| .characters |= map(select(.Last == $last))
'