Skip to content

Commit 8ea4a55

Browse files
committed
Allow variable refs as object keys {$key:value}
Users are often surprised by the requirement to parenthesize any non-trivial object key expressions in object constructors. E.g., {"a"+"b":1}. This commit adds one more kind of key expression besides literals and idents: variable references. A common use case for this is jq programs as JSON templates to fill in with variables computed from inputs or passed in on the command-line. E.g., {some_key:$value}. Now users can also use, e.g., {$key:$value}. This and the restrictions on key and value expressions in object constructors are now clarified a bit in the documentation.
1 parent bb87e6e commit 8ea4a55

File tree

3 files changed

+606
-582
lines changed

3 files changed

+606
-582
lines changed

docs/content/3.manual/manual.yml

+19-6
Original file line numberDiff line numberDiff line change
@@ -549,13 +549,16 @@ sections:
549549
dictionaries or hashes), as in: `{"a": 42, "b": 17}`.
550550
551551
If the keys are "identifier-like", then the quotes can be left
552-
off, as in `{a:42, b:17}`. Keys generated by expressions need
553-
to be parenthesized, e.g., `{("a"+"b"):59}`.
552+
off, as in `{a:42, b:17}`. Variable references as key
553+
expressions use the value of the variable as the key. Key
554+
expressions other than constant literals, identifiers, or
555+
variable references, need to be parenthesized, e.g.,
556+
`{("a"+"b"):59}`.
554557
555-
The value can be any expression (although you may need to
556-
wrap it in parentheses if it's a complicated one), which gets
557-
applied to the {} expression's input (remember, all filters
558-
have an input and an output).
558+
The value can be any expression (although you may need to wrap
559+
it in parentheses if, for example, it contains colons), which
560+
gets applied to the {} expression's input (remember, all
561+
filters have an input and an output).
559562
560563
{foo: .bar}
561564
@@ -593,6 +596,16 @@ sections:
593596
594597
{"stedolan": ["JQ Primer", "More JQ"]}
595598
599+
Variable references as keys use the value of the variable as
600+
the key. Without a value then the variable's name becomes the
601+
key and its value becomes the value,
602+
603+
"f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}
604+
605+
produces
606+
607+
{"f o o":"f o o","b a r":"f o o"}
608+
596609
examples:
597610
- program: '{user, title: .titles[]}'
598611
input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'

0 commit comments

Comments
 (0)