Skip to content

Commit

Permalink
Allow variable refs as object keys {$key:value}
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
nicowilliams committed Dec 11, 2018
1 parent bb87e6e commit 8ea4a55
Show file tree
Hide file tree
Showing 3 changed files with 606 additions and 582 deletions.
25 changes: 19 additions & 6 deletions docs/content/3.manual/manual.yml
Original file line number Diff line number Diff line change
Expand Up @@ -549,13 +549,16 @@ sections:
dictionaries or hashes), as in: `{"a": 42, "b": 17}`.
If the keys are "identifier-like", then the quotes can be left
off, as in `{a:42, b:17}`. Keys generated by expressions need
to be parenthesized, e.g., `{("a"+"b"):59}`.
off, as in `{a:42, b:17}`. Variable references as key
expressions use the value of the variable as the key. Key
expressions other than constant literals, identifiers, or
variable references, need to be parenthesized, e.g.,
`{("a"+"b"):59}`.
The value can be any expression (although you may need to
wrap it in parentheses if it's a complicated one), which gets
applied to the {} expression's input (remember, all filters
have an input and an output).
The value can be any expression (although you may need to wrap
it in parentheses if, for example, it contains colons), which
gets applied to the {} expression's input (remember, all
filters have an input and an output).
{foo: .bar}
Expand Down Expand Up @@ -593,6 +596,16 @@ sections:
{"stedolan": ["JQ Primer", "More JQ"]}
Variable references as keys use the value of the variable as
the key. Without a value then the variable's name becomes the
key and its value becomes the value,
"f o o" as $foo | "b a r" as $bar | {$foo, $bar:$foo}
produces
{"f o o":"f o o","b a r":"f o o"}
examples:
- program: '{user, title: .titles[]}'
input: '{"user":"stedolan","titles":["JQ Primer", "More JQ"]}'
Expand Down
Loading

0 comments on commit 8ea4a55

Please sign in to comment.