Reputation: 13
Is it possible to use a variable to hold a dot notation path? (I'm probably not using the correct term.)
For example, given the following json:
{
"people": [
{
"names": {
"given": "Alice",
"family": "Smith"
},
"id": 47
},
{
"id": 42
}
]
}
Is it possible to construct something like:
.names.given as $ng | .people[] | select(.id==47) | ($ng)
and output "Alice"?
The idea is to allow easier modification of a complex expression. I've tried various parens and quotes with increasing literal results ('.names.given' and '$ng')
Upvotes: 1
Views: 1163
Reputation: 116780
The answer is no and yes: as you've seen, once you write an expression such as .names.given as $ng
, $ng holds the JSON values, not the path.
But jq does support path expressions
in the form of arrays of strings and/or non-negative integers. These can be used to access values in conjunction with the built-in getpath/1
.
So you could, for example, write something along the lines of:
["names", "given"] as $ng
| .people[]
| select(.id==47)
| getpath($ng)
It's possible to convert a "dot notation" path into an "array path" using path/1
; e.g. the assignment to $ng above could be written as:
(null | path(.names.given)) as $ng
Upvotes: 2
Reputation: 5516
Your question and the example you provided seems very confusing to me. The jist that I got is that you want to assign a name to a value obtained from dot notation and then use it at a later point in time.
See if this is of any help -
.people | map(select(.id = 47))[0].names.given as $ng | $ng
Upvotes: -1