Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq delete function doesn't work with variable

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading