Python 什么';如果第一个JSON键不存在,那么使用JMESPath选择另一个JSON键的最佳方法是什么?
例如,JSON包含一些产品数据:Python 什么';如果第一个JSON键不存在,那么使用JMESPath选择另一个JSON键的最佳方法是什么?,python,json,jmespath,Python,Json,Jmespath,例如,JSON包含一些产品数据: { "sku": 123, "product": { "name": "Some name", "images": { "normalImage": "http://somelink.com/1.jpg", "bigImage": "http://somelink.com/1b.jpg" } } } 我想选择图像链接,但bigImage仅存在于某些产品中,因此有时我需要选择normalImage 显而
{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg",
"bigImage": "http://somelink.com/1b.jpg"
}
}
}
我想选择图像链接,但bigImage
仅存在于某些产品中,因此有时我需要选择normalImage
显而易见的解决方案如下所示:
jmespath.search('product.images.bigImage') or jmespath.search('product.images.normalImage')
但我觉得可以做得更好。如何使用JMESPath语法以最佳方式执行此操作?您可以创建一个
CustomFunctions
类来执行此操作,类似于本页中给出的示例
product.images.[bigImage, normalImage][?@]|[0]
将打印出以下结果:
Test1: http://somelink.com/1b.jpg # When bigImage key exists
Test2: http://somelink.com/1.jpg # When bigImage key doesn't exist
如果JMESPath变得太复杂,我们可以始终使用好的旧标准字典方法:
def test2(json):
json_dict = loads(json)
images = json_dict["product"]["images"]
return images.get("bigImage", images["normalImage"])
# TEST 1 - bigImage key exists
json1 = """{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg",
"bigImage": "http://somelink.com/1b.jpg"
}
}
}"""
print("Test1: %s" % test2(json1))
# TEST 2 - bigImage key doesn't exist
json2 = """{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg"
}
}
}"""
print("Test2: %s" % test2(json2))
也会打印相同的结果:
Test1: http://somelink.com/1b.jpg # When bigImage key exists
Test2: http://somelink.com/1.jpg # When bigImage key doesn't exist
您可以创建一个
CustomFunctions
类来执行此操作,类似于页面中给出的示例
将打印出以下结果:
Test1: http://somelink.com/1b.jpg # When bigImage key exists
Test2: http://somelink.com/1.jpg # When bigImage key doesn't exist
如果JMESPath变得太复杂,我们可以始终使用好的旧标准字典方法:
def test2(json):
json_dict = loads(json)
images = json_dict["product"]["images"]
return images.get("bigImage", images["normalImage"])
# TEST 1 - bigImage key exists
json1 = """{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg",
"bigImage": "http://somelink.com/1b.jpg"
}
}
}"""
print("Test1: %s" % test2(json1))
# TEST 2 - bigImage key doesn't exist
json2 = """{
"sku": 123,
"product": {
"name": "Some name",
"images": {
"normalImage": "http://somelink.com/1.jpg"
}
}
}"""
print("Test2: %s" % test2(json2))
也会打印相同的结果:
Test1: http://somelink.com/1b.jpg # When bigImage key exists
Test2: http://somelink.com/1.jpg # When bigImage key doesn't exist
如果只使用JMESPath语法,那么下面的内容如何
product.images.[bigImage, normalImage][?@]|[0]
我们的想法是,我们将所有想要使用的图像按优先顺序排列成一个数组,过滤掉缺失的图像,然后在剩余的数组中选择第一个项目
警告-这不区分缺失值和
null
(或其他“假”值,如空字符串),因此,如果这对您的特定情况很重要,您可能需要对其进行一些调整。以下仅使用JMESPath语法如何
product.images.[bigImage, normalImage][?@]|[0]
我们的想法是,我们将所有想要使用的图像按优先顺序排列成一个数组,过滤掉缺失的图像,然后在剩余的数组中选择第一个项目
警告-这不区分缺失值和null
(或其他“假”值,如空字符串),因此,如果这对您的特定情况很重要,您可能需要对其进行一些调整