亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果使用 JMESPath 選擇另一個 JSON 密鑰,則選擇第一個 JSON 密鑰的最佳方法是

如果使用 JMESPath 選擇另一個 JSON 密鑰,則選擇第一個 JSON 密鑰的最佳方法是

一只萌萌小番薯 2022-09-13 19:14:39
例如,有一些包含一些產品數據的 JSON:{  "sku": 123,  "product": {    "name": "Some name",    "images": {      "normalImage": "http://somelink.com/1.jpg",      "bigImage": "http://somelink.com/1b.jpg"    }  }}我想選擇圖像鏈接,但僅存在于某些產品中,因此有時我需要選擇。bigImagenormalImage顯而易見的解決方案是這樣的:jmespath.search('product.images.bigImage') or jmespath.search('product.images.normalImage')但我覺得可以做得更好。如何使用 JMESPath 語法以最佳方式執行此操作?
查看完整描述

2 回答

?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

以下僅使用 JMESPath 語法的情況如何?

product.images.[bigImage, normalImage][?@]|[0]

我們的想法是,我們按照偏好順序制作一個要使用的所有圖像的數組,過濾掉丟失的圖像,然后選擇剩余數組中的第一個項目。

警告 - 這不會區分缺失值和(或其他“錯誤”值,例如空字符串),因此,如果這對您的特定情況很重要,則可能需要對其進行一些調整。null


查看完整回答
反對 回復 2022-09-13
?
胡說叔叔

TA貢獻1804條經驗 獲得超8個贊

您可以創建一個類來執行此操作,類似于 GitHub 頁面中給出的示例。CustomFunctions


from jmespath import search

from jmespath import functions

from jmespath import Options


from json import loads


class CustomFunctions(functions.Functions):


    # Method that selects 'bigImage' key value if it exists

    # Otherwise return 'normalImage' value

    # dict.get() is perfect for this, since it returns a default value if a key doesn't exist

    # Use type 'object' since thats the equivalant type to a Python dictionary in JSON

    # Make sure to decorate function signature as well to indicate types

    # Make sure to also put _func_ before your function name

    @functions.signature({'types': ['object']})

    def _func_choose_key(self, d):

        return d.get('bigImage', d['normalImage'])


if __name__ == "__main__":


    # Get custom function options

    options = Options(custom_functions=CustomFunctions())


    # Test method which runs JMESPath query with custom function

    def test(json):

        json_dict = loads(json)

        return search('product.images | choose_key(@)', json_dict, options=options)



    # 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" % test(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" % test(json2))

這將打印出以下結果:


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


查看完整回答
反對 回復 2022-09-13
  • 2 回答
  • 0 關注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號