user915534
user915534

Reputation: 49

jq: pass string argument without quotes

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.

Upvotes: 2

Views: 6511

Answers (3)

peak
peak

Reputation: 116870

Since jq does not have an “eval” function, the appropriate way to specify a path programmatically in jq is using a JSON array in conjunction with jq’s getpath and setpath built-ins, as appropriate.

Thus in your case you could use the -—argjson command-line option to pass in the path of interest, e.g.

-—argson p '["properties"]'

and your jq program would use getpath($p).

Needless to say, this approach works for arbitrarily nested paths.

Upvotes: 1

gregory
gregory

Reputation: 12953

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

Upvotes: 5

hobbs
hobbs

Reputation: 240314

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.

Upvotes: 2

Related Questions