为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查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 关注
  • 314 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信