Josh Cooley
Josh Cooley

Reputation: 362

jq returns "Invalid numeric literal" with --arg

The command below is returning an error (jq version: 1.6):

$ jq --arg b bar . <<< '{ "foo": $b }'
parse error: Invalid numeric literal at line 1, column 12

Expected output:

{
  "foo": "bar"
}

The jq 1.6 manual describes the --arg option thusly:

  • --arg name value:

This option passes a value to the jq program as a predefined variable. If you run jq with --arg foo bar, then $foo is available in the program and has the value "bar". Note that value will be treated as a string, so --arg foo 123 will bind $foo to "123".

Named arguments are also available to the jq program as $ARGS.named.

My usage appears correct. What's going on here?

Upvotes: 0

Views: 511

Answers (1)

Josh Cooley
Josh Cooley

Reputation: 362

My variable call was not within the jq program

The here-string I'm passing into jq

{ "foo": $b }

is not "the jq program" mentioned in the manual's --arg description. The lone . was the entire program, and did not use the variable $b.

I was trying to construct JSON from scratch by passing in my pattern on stdin. Instead, I should have provided the --null-input option, and replaced the . with the pattern I was attempting to pass in.

Description of --null-input

  • --null-input/-n:

Don't read any input at all! Instead, the filter is run once using null as the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch.

Here's the correct invocation:

$ jq --arg b bar --null-input '{ "foo": $b }'
{
  "foo": "bar"
}

Upvotes: 2

Related Questions