2

I'm trying out this command jq -n --arg KEY 'no leading zero' --arg VAL '.13452' '.+={$KEY:$VAL}' on bash terminal to produce output {"no leading zero":".13452"}.

But I get the following error:

jq: error: syntax error, unexpected ':', expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.+={$KEY:$VAL}        
jq: error: May need parentheses around object key expression at <top-level>, line 1:
.+={$KEY:$VAL}    
jq: 2 compile errors

How to fix the command so I get the output {"no leading zero":".13452"} using the args?

Thanks.

4
  • What is the question? Jan 18, 2022 at 5:47
  • To produce the output as stated.
    – Logan Lee
    Jan 18, 2022 at 5:51
  • That's not a question. Please reword what you posted so it is in the form of a question. This is a questions and answers site. Jan 18, 2022 at 5:56
  • OK. Edited the question.
    – Logan Lee
    Jan 18, 2022 at 5:58

2 Answers 2

2

You can use string interpolation:

jq -n --arg KEY 'no leading zero' --arg VAL '.13452' '{"\($KEY)":$VAL}'

which produces

{
  "no leading zero": ".13452"
}
1
  • 1
    '{ ($KEY) : $VAL}' seems to also work. In any case, it's not about shell quoting. Jan 18, 2022 at 6:15
1

You most commonly add a key and a corresponding value to an object in jq in one of three ways.

  1. You "add" an object with the key and value to the existing object, as you have shown (. += { key: value }), or
  2. You create the key and assign the value directly in the existing object (.key = value), or
  3. If you name your variables intelligently when using --arg, you could simply use $ARGS.named and add that (. += $ARGS.named).

In the first case, when using variables, the key will be taken as an expression that is evaluated, which means that it will need to have parentheses around it (the error message hints directly at this fact):

. += { ($key): $value }

For example:

jq -n --arg key 'no leading zero' --arg value '.13452' '{ ($key): $value }'

(note that we have no object to add to, so . += is not needed)


In the second case, you should use the .[$key] syntax:

.[$key] = $value

For example:

jq -n --arg key 'no leading zero' --arg value '.13452' '.[$key] = $value'

In the third case, use

. += $ARGS.named

For example:

jq -n --arg 'no leading zero' '.13452' '$ARGS.named'

(note that we have no object to add to, so . += is not needed)


You could also use jo, which makes for a simpler syntax in this case, or at least a shorter command:

jo -- -s 'no leading zero'=.13452

(The -s ensures that the number is interpreted as a string.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .