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

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

如何檢查python中存在的JSON鍵/對象

如何檢查python中存在的JSON鍵/對象

開心每一天1111 2021-12-21 16:45:39
我對python很陌生。除了我的以下代碼之外,是否還有檢查python中存在的特定JSON對象?承認我下面的代碼不是很好的做法所以需要知道哪種方法更好檢查和易于維護?這是 JSON 響應:[  {    "MessageId": "250e37a8-d779-48a1-9941-84219a82513e",    "ReceiptHandle": "AQEBjualXe2ywqTgIVmCNI5sKj7r48werf84HHA2BWZimwiEXLFxA/MiPBclK048NZBtOnM3dSDfoiwwqoNTPxTRz+IChd8McziweCxHX6texjAOi/MyAQjCWP+2hJPoxzQgXx9kjnKbepKlcgxhpOiQZe6WiSIq0dXwHHXSA7SP0g9NIR/dU38b+wmo0m2q7MNVfSct967EKF49wow9RHyFMO8iD8fH93PYT9om5NdUha3dvkWnisKcfuO5pZY3LLXPAnuZT/VfqxJjmPqb98iepBfqFb6SpM/02IVSql81XKJEbMBc4zPHp/Uace6e4UDGsn/hPCVsqQsTzrbKCR+ovpkhXipWwTYSlgsLe/o43k0UxhCN8eKhg835KuUkskA3T8C5Q6v6xgznlR7JJuhZpg==",    "MD5OfBody": "bbdc5fdb8be7251f5c910905db994bab",    "Body": "Information about current NY Times fiction bestseller for week of 12/11/2016.",    "Attributes": {      "SentTimestamp": "1553851566164"    },    "MD5OfMessageAttributes": "d25a6aea97eb8f585bfa92d314504a92",    "MessageAttributes": {      "Author": {        "StringValue": "John Grisham",        "DataType": "String"      },      "Title": {        "StringValue": "The Whistler",        "DataType": "String"      },      "WeeksOn": {        "StringValue": "6",        "DataType": "Number"      }    }  }]這是我要檢查的python代碼:if 'Messages' in response:    message = response['Messages'][0]    receipt_handle = message['ReceiptHandle']    sqs.delete_message(        QueueUrl=queue_url,        ReceiptHandle=receipt_handle    )    print('Received and deleted message: %s' % message)else:    print('Message not received yet')請讓我知道上面的代碼是否是好的做法。
查看完整描述

3 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

您可以結帳的另一個選項是我在使用 JSON 數據時實際上更喜歡的選項,是從 JSON 數據中創建一個對象并使用該hasattr方法。這將防止您開始過度使用 try-except 塊,還可以使您的代碼更易于理解。使用您的數據的示例如下:


data= '''

  {

"MessageId": "250e37a8-d779-48a1-9941-84219a82513e",

"ReceiptHandle": "AQEBjualXe2ywqTgIVmCNI5sKj7r48werf84HHA2BWZimwiEXLFxA/MiPBclK048NZBtOnM3dSDfoiwwqoNTPxTRz+IChd8McziweCxHX6texjAOi/MyAQjCWP+2hJPoxzQgXx9kjnKbepKlcgxhpOiQZe6WiSIq0dXwHHXSA7SP0g9NIR/dU38b+wmo0m2q7MNVfSct967EKF49wow9RHyFMO8iD8fH93PYT9om5NdUha3dvkWnisKcfuO5pZY3LLXPAnuZT/VfqxJjmPqb98iepBfqFb6SpM/02IVSql81XKJEbMBc4zPHp/Uace6e4UDGsn/hPCVsqQsTzrbKCR+ovpkhXipWwTYSlgsLe/o43k0UxhCN8eKhg835KuUkskA3T8C5Q6v6xgznlR7JJuhZpg==",

"MD5OfBody": "bbdc5fdb8be7251f5c910905db994bab",

"Body": "Information about current NY Times fiction bestseller for week of 12/11/2016.",

"Attributes": {"SentTimestamp": "1553851566164"},

"MD5OfMessageAttributes": "d25a6aea97eb8f585bfa92d314504a92",

"MessageAttributes": {"Author": {"StringValue": "John Grisham","DataType": "String"},"Title": {"StringValue": "The Whistler","DataType": "String"},"WeeksOn": {"StringValue": "6","DataType": "Number"}}

  } '''


import json


class Response:


    def __init__(self, data):

        self.__dict__ = json.loads(data)


response = Response(data)


if hasattr(response , 'MessageId'):

    receipt_handle = response.ReceiptHandle

    print("Received and deleted message: %s" % response.MessageId)


else:

    print('Message not received yet')

輸出:


Received and deleted message: 250e37a8-d779-48a1-9941-84219a82513e


查看完整回答
反對 回復 2021-12-21
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

由于響應是listdict 的:


j_data = [{'MessageId': '250e37a8-d779-48a1-9941-84219a82513e',

           'ReceiptHandle': 'AQEBjualXJJuhZpg==', 'MD5OfBody': 'bbdc5f905db994bab',

           'Body': 'Information about current NY Times fiction bestseller for week of 12/11/2016.',

           'Attributes': {'SentTimestamp': '1553851566164'},

           'MD5OfMessageAttributes': 'd25a6aea97eb8f585bfa92d314504a92',

           'MessageAttributes': {'Author': {'StringValue': 'John Grisham', 'DataType': 'String'},

                                 'Title': {'StringValue': 'The Whistler', 'DataType': 'String'},

                                 'WeeksOn': {'StringValue': '6', 'DataType': 'Number'}}}

            ]




for data in j_data:

    try:

        if 'MessageId' in data:

            message = data['MessageId']

            receipt_handle = data['ReceiptHandle']

            sentTimeStamp = data['Attributes']['SentTimestamp']

            print(message)

            print(receipt_handle)

            print(sentTimeStamp)

    except KeyError:

        print("Some custom message here")

輸出:


250e37a8-d779-48a1-9941-84219a82513e

AQEBjualXJJuhZpg==

1553851566164

編輯:


另一種方法是在訪問之前檢查每個鍵,即(ReceiptHandle從響應中刪除elem):


j_data = [{'MessageId': '250e37a8-d779-48a1-9941-84219a82513e',

           'MD5OfBody': 'bbdc5f905db994bab',

           'Body': 'Information about current NY Times fiction bestseller for week of 12/11/2016.',

           'Attributes': {'SentTimestamp': '1553851566164'},

           'MD5OfMessageAttributes': 'd25a6aea97eb8f585bfa92d314504a92',

           'MessageAttributes': {'Author': {'StringValue': 'John Grisham', 'DataType': 'String'},

                                 'Title': {'StringValue': 'The Whistler', 'DataType': 'String'},

                                 'WeeksOn': {'StringValue': '6', 'DataType': 'Number'}}}

            ]




for data in j_data:

    try:

        if 'MessageId' in data:

            message = data['MessageId']

            print(message)

        if 'ReceiptHandle' in data:

            receipt_handle = data['ReceiptHandle']

            print(receipt_handle)

        if 'Attributes' in data:

            sentTimeStamp = data['Attributes']['SentTimestamp']

            print(sentTimeStamp)

    except KeyError:

        print("Some custom message here")

輸出:


250e37a8-d779-48a1-9941-84219a82513e

1553851566164


查看完整回答
反對 回復 2021-12-21
?
慕后森

TA貢獻1802條經驗 獲得超5個贊

首先,正如已經提到的,示例 json 不包含 key Messages。我認為你的代碼看起來不錯。但是,如果您有一個沒有密鑰的 json 的情況Messages非常罕見,我會嘗試除了塊。


try:

    message = response['Messages'][0]

    receipt_handle = message['ReceiptHandle']


    sqs.delete_message(

        QueueUrl=queue_url,

        ReceiptHandle=receipt_handle

    )

    print('Received and deleted message: %s' % message)

except KeyError:

    print('Message not received yet')

每次獲得“正確”的 json 時,這都會快得多。但是當你得到一個缺少密鑰的 json 時會變慢。因此,也許您需要了解是否經常出現缺少密鑰的天氣。


但這取決于用例。而我的回答只是我個人在類似用例中的看法和經驗


查看完整回答
反對 回復 2021-12-21
  • 3 回答
  • 0 關注
  • 345 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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