Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass literal variable templates to jq from within Make?

I'm trying to use jq within a Makefile to generate a json file. Here is a sample Makefile

foo.json:
    jq -n --arg x "bar" '{"foo": "$$x"}' > foo.json
    @cat foo.json
    @rm foo.json

When I run this with GNU Make v4.3 and jq v1.6 I get the following

make
jq -n --arg x "bar" '{"foo": "$x"}' > foo.json
{
  "foo": "$x"
}

Notice that $x shows up literally and doesn't get interpolated by jq. How do I achieve the following...

make
jq -n --arg x "bar" '{"foo": "$x"}' > foo.json
{
  "foo": "bar"
}
like image 770
Trey Stout Avatar asked Oct 29 '25 05:10

Trey Stout


2 Answers

You simply don't need to wrap your variable in quotes:

jq -n --arg x "bar" '{foo: $x}'

Or use string interpolation:

jq -n --arg x "bar" '{foo: "\($x)"}'
like image 52
customcommander Avatar answered Oct 31 '25 08:10

customcommander


I ended up avoiding jq --arg entirely and went with a simpler approach.

Example Makefile:

# the arg to pass to jq
SOME_VAR?=my-var

foo.json:
    jq -n  '{"foo": "'"$(SOME_VAR)"'"}' > foo.json
    @cat foo.json
    @rm foo.json

Example usage:

$ make foo.json
jq -n  '{"foo": "'"my-var"'"}' > foo.json
{
  "foo": "my-var"
}

Quoted variables work too:

$ SOME_VAR="hi" make foo.json
jq -n  '{"foo": "'"hi"'"}' > foo.json
{
  "foo": "hi"
}
like image 30
mfink Avatar answered Oct 31 '25 06:10

mfink



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!