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