I’m trying to pass a variable to a jq delete function. It doesn’t work with the variable, but does work if hard-coded. Could someone help me understand what I’m doing wrong.
Doesn’t work:
echo '{"profiles": {"a":"1", "b":"2"}}' | jq --arg a '.a' '.profiles | del($a)'
Works:
echo '{"profiles": {"a":"1", "b":"2"}}' | jq '.profiles | del(.a)'
>Solution :
You can only pass raw strings (with the --arg option) or JSON-encoded strings (with the --argjson option) as arguments. You cannot pass jq code as a variable (and evaluate it inside jq).
You can, however, reference fields by their string representation. Thus, just use the field name as argument, and .[$var] to address it:
echo '{"profiles": {"a":"1", "b":"2"}}' | jq --arg a 'a' '.profiles | del(.[$a])'
{
"b": "2"
}