There's JSON with some product data, as an example:
{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg",
"bigImage": "http://somelink.com/1b.jpg"
}
}
}
I want to pick the image link, but bigImage
exists only in some products, so sometimes I need to pick normalImage
instead.
The obvious solution looks like:
jmespath.search('product.images.bigImage') or jmespath.search('product.images.normalImage')
but I feel it could be done better. How to do it in an optimal way using JMESPath syntax?
How about the following for using only JMESPath syntax?
product.images.[bigImage, normalImage][?@]|[0]
The idea being that we make an array of all the images we want to use in order of preference, filter out the ones that are missing, then pick the first item in the remaining array.
Caveat - this doesn't distinguish between missing and null
(or other "falsey" values, such as empty strings) so you might need to tweak it a bit if that matters to you for your particular case.