From ES2015 with puted properties and Array.reduce/Array.map/Object.assign you can do:
[{name: 'foo', age: 43}, {name: 'bar', age: 55}].map(
o => ({[o.name]: o.age})).reduce((a, b) => Object.assign(a,b), {})
…and get:
{ foo: 43, bar: 55 }
How do I get this from JMESPath?
Attempt:
$echo '[{"name": "foo", "age": 43}, {"name": "bar", "age": 55}]' | jp [].{name:age}
[
{
"name": 43
},
{
"name": 55
}
]
From ES2015 with puted properties and Array.reduce/Array.map/Object.assign you can do:
[{name: 'foo', age: 43}, {name: 'bar', age: 55}].map(
o => ({[o.name]: o.age})).reduce((a, b) => Object.assign(a,b), {})
…and get:
{ foo: 43, bar: 55 }
How do I get this from JMESPath?
Attempt:
$echo '[{"name": "foo", "age": 43}, {"name": "bar", "age": 55}]' | jp [].{name:age}
[
{
"name": 43
},
{
"name": 55
}
]
Share
Improve this question
edited Feb 4, 2021 at 21:07
dreftymac
32.4k26 gold badges124 silver badges188 bronze badges
asked Jul 21, 2017 at 11:51
A TA T
13.8k23 gold badges107 silver badges168 bronze badges
2 Answers
Reset to default 8Problem
- How to construct a Jmespath query that returns objects with arbitrary key-value pairs
- The keys need to be dynamic, based on the output of a jmespath filter expression
Workaround
- As of this writing (2019-03-22), dynamic keys are not available in standard Jmespath
- However, it is possible to return a list of lists instead of a list of objects, and simply post-process that list of lists outside of jmespath
Example
[*].[@.name,@.age]
Returns
[['foo', 43], ['bar', 55]]
Which can then be post-processed outside of Jmespath, if that is an option for you.
See also
- github issue about this exact use-case
To get this result precisely:
{ "foo": 43, "bar": 55 }
You should use this query:
@.{foo: @[0].age, bar: @[1].age}
But as you can see I don't retrieve the keys foo
and bar
dynamically because I can't do it in JMESPath.