10

从具有计算属性Array.reduce / Array.map / Object.assign 的ES2015 开始,您可以执行以下操作:

[{name: 'foo', age: 43}, {name: 'bar', age: 55}].map(
    o => ({[o.name]: o.age})).reduce((a, b) => Object.assign(a,b), {})

......并得到:

{ foo: 43, bar: 55 }

我如何从 JMESPath 获得这个?


试图:

$echo '[{"name": "foo", "age": 43}, {"name": "bar", "age": 55}]' | jp [].{name:age}
[
  {
    "name": 43
  },
  {
    "name": 55
  }
]
4

2 回答 2

4

Problem

  • 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

于 2019-03-23T02:22:21.467 回答
0

要准确地得到这个结果:{ foo: 43, bar: 55 },你应该使用这个查询:

@.{foo: @[0].age, bar: @[1].age}

但是正如您所看到的,我没有动态检索键 foo 和 bar 因为我不能在 JMES 路径中这样做

于 2019-07-23T08:44:33.467 回答