Skip to main content
added 311 characters in body
Source Link
jesse_b
  • 41.6k
  • 14
  • 108
  • 162

You can accomplish this by wrapping $n in parenthesis to tell jq to evaluate the expression:

n="foo"; echo "{}" | jq --arg n "$n" '. += { ($n): $n }'

Or probably better suited for this task would be jo(1):

$ jo "$n"="$n"
{"foo":"foo"}

I'm not sure if the documentation is just wrong or if my ability to comprehend is not at a high enough level but it does seem to say that your example should work:

Key expressions other than constant literals, identifiers, or variable references, need to be parenthesized, e.g., {("a"+"b"):59}.

And one might assume that is referring to a jq native variable rather than one injected by the shell as they are slightly different, but alas both need to be parenthesized:

$ echo '{}' | jq 'def myvar: "foo"; {myvar: myvar}'
{
  "myvar": "foo"
}
$ echo '{}' | jq 'def myvar: "foo"; {(myvar): myvar}'
{
  "foo": "foo"
}

You can accomplish this by wrapping $n in parenthesis to tell jq to evaluate the expression:

n="foo"; echo "{}" | jq --arg n "$n" '. += { ($n): $n }'

Or probably better suited for this task would be jo(1):

$ jo "$n"="$n"
{"foo":"foo"}

You can accomplish this by wrapping $n in parenthesis to tell jq to evaluate the expression:

n="foo"; echo "{}" | jq --arg n "$n" '. += { ($n): $n }'

Or probably better suited for this task would be jo(1):

$ jo "$n"="$n"
{"foo":"foo"}

I'm not sure if the documentation is just wrong or if my ability to comprehend is not at a high enough level but it does seem to say that your example should work:

Key expressions other than constant literals, identifiers, or variable references, need to be parenthesized, e.g., {("a"+"b"):59}.

And one might assume that is referring to a jq native variable rather than one injected by the shell as they are slightly different, but alas both need to be parenthesized:

$ echo '{}' | jq 'def myvar: "foo"; {myvar: myvar}'
{
  "myvar": "foo"
}
$ echo '{}' | jq 'def myvar: "foo"; {(myvar): myvar}'
{
  "foo": "foo"
}
Source Link
jesse_b
  • 41.6k
  • 14
  • 108
  • 162

You can accomplish this by wrapping $n in parenthesis to tell jq to evaluate the expression:

n="foo"; echo "{}" | jq --arg n "$n" '. += { ($n): $n }'

Or probably better suited for this task would be jo(1):

$ jo "$n"="$n"
{"foo":"foo"}