1

I have such object, I need to evaluate which is "cheapest" with jmespath

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

the output should be: 'a' object

i am doing:

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

but no luck

Jesus_Maria
  • 1,137
  • 5
  • 14
  • 24
  • `wines` is a key/value pair in an object, so wouldn't it be `min_by(obj.wines, &price1, &price2).name` (if your object is called `obj`). I'm not familiar with jmespath so this is a guess. – Andy Dec 14 '15 at 16:50
  • no, this is just an example you are right, problem is in calculating a sum @Andy – Jesus_Maria Dec 14 '15 at 16:58
  • Can you clarify how you calculate cheapest? Is it the item that has the lowest value of `price1` and `price2`? Or is whichever item has the lowest value of `price1+price2`? – jamesls Dec 14 '15 at 22:52

1 Answers1

1

Depending on what you mean by cheapest, if you want to pick the item that has the minimum value of price1 and price2 combined, you can use: 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"
}

The & needs to be at the beginning of the second argument because the expected type is an expression reference. The &sum([price1,price2]) is saying that for each item in the wines array, evaluate the expression sum([price1,price2]) and use the resulting value to determine which item in the array is the minimum.

As another example, if you wanted to select the item in the wines list that had the lowest price of either price1 or price2, you could replace sum with 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"
}
jamesls
  • 5,428
  • 1
  • 28
  • 17