1

我有这样的对象,我需要用 jmespath 评估哪个“最便宜”

{
  "wines": [
    {
      "name": "b",
      "price1": 30,
      "price2": 110
    },
    {
      "name": "a",
      "price1": 50,
      "price2": 1
    },
    {
      "name": "c",
      "price1": 40,
      "price2": 1130
    }
  ]
}

输出应该是:'a'对象

我在做:

min_by(wines, &price1, &price2).name
min_by(wines, &price1).name
min_by(wines, sum(&price1, &price2)).name

但没有运气

4

1 回答 1

1

根据你所说的最便宜的意思,如果你想选择 price1 和 price2 组合的最小值的项目,你可以使用min_by(wines, &sum([price1,price2]))

$ echo '{
  "wines": [
    {
      "name": "b",
      "price1": 30,
      "price2": 110
    },
    {
      "name": "a",
      "price1": 50,
      "price2": 1
    },
    {
      "name": "c",
      "price1": 40,
      "price2": 1130
    }
  ]
}' | jp 'min_by(wines, &sum([price1,price2]))'

{
    "price2": 1,
    "price1": 50,
    "name": "a"
}

&需要在第二个参数的开头,因为预期的类型是表达式引用。&sum([price1,price2])也就是说,对于数组中的每一项,wines计算表达式sum([price1,price2])并使用结果值来确定数组中的哪一项是最小值。

再举一个例子,如果您想在酒单中选择价格最低的 或 的项目 price1price2可以替换summin

$ echo '{
  "wines": [
    {
      "name": "b",
      "price1": 30,
      "price2": 110
    },
    {
      "name": "a",
      "price1": 50,
      "price2": 1
    },
    {
      "name": "c",
      "price1": 40,
      "price2": 1130
    }
  ]
}' | jp 'min_by(wines, &min([price1,price2]))'

{
    "price2": 1,
    "price1": 50,
    "name": "a"
}
于 2015-12-14T23:09:03.663 回答