我有这样的对象,我需要用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


但没有运气

最佳答案

根据您最便宜的意思,如果您要选择价格最低的价格与价格最低的价格相结合的商品,可以使用: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,则可以将sum替换为min

$ 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"
}

08-27 02:04