Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: pass string argument without quotes

Tags:

jq

I would like to pass an argument without quotes (JQ arg has double quotes by default) since it should be used as a filter. For e.g.

propt='.properties'
final=($(jq -r -c --arg p $propt '$p' sample.json))
echo $final

sample.json

{
  "type": "object",
  "description": "Contains information",
  "properties": {
    "type": {
      "description": "Type"
        }
   }
}

So ultimately it prints out .properties instead of the expected {"type":{"description":"Type"}} I use a bash shell for this purpose.

Please let me know what I am doing wrong.

like image 333
user915534 Avatar asked Feb 16 '26 03:02

user915534


2 Answers

If I understand you correctly, you're getting sidetracked by thinking you need to set up a variable in jq, instead of just letting the shell do an expansion:

% foo='.properties'
% jq -r -c  "$foo" sample.json 

output:

{"type":{"description":"Type"}}

Note the double quotes on $foo to still allow the shell to expand the variable to .properties. That said you could unsafely use: jq -r -c $foo sample.json

like image 100
gregory Avatar answered Feb 20 '26 18:02

gregory


You can't use --arg in that way. The value of a --arg is a string, not a jq filter expression. If you do --arg p .properties, then $p will contain the string ".properties", it won't be evaluated as a program. Find a different way to do what you want, perhaps by defining a function.

For example, if you prefixed your program with def p: .properties; then you could use .|p in your program in the way that you're using $p now, and it would access the .properties of whatever value is in context.

like image 34
hobbs Avatar answered Feb 20 '26 16:02

hobbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!