For example, I have this json file:
[
{
"Name": "Bob",
"Grade": "Pass"
},
{
"Name": "Alice",
"Grade": "Fail"
},
{
"Name": "Mallory",
"Grade": "Fail"
}
]
And this array ["Bo", "Al"]
How do I loop through the array to check the json file for those students only and output their {Name, Grade}?
Also a note, I can do a series of pipes of select(test(.Name == "Bob"))
but I can't hardcode it as the array is being generated dynamically depending on a selection.
Let me know if you need further clearance.
Thank you!
Note: Edited to ask how to do this for substrings, like "Bo" and "Al" for "Bob" and "Alice". Apologies as I'm really quite new to jq advanced topics. Thank you again!
Adopting the answer from the linked question in comments with slight modification to suit the use-case of OP
jq -n --argjson names '["Bob", "Alice"]' '
(reduce $names[] as $name ({}; .[$name] = true)) as $set
| inputs | map(select($set[.Name]))' json
The reduce
function basically creates a hash-map of truth values mapped for each entry of your input names array. Later apply the map on each of the input object. If the condition satisfies, print the object desired.
Or alternatively use the any/2
function
jq --argjson names '["Bob", "Alice"]' '
map(select( .Name as $a | any( $names[]; . == $a) ))' json