2

I'm very new to python. Is there anyway to check specific JSON object exist in python except my following code? Admit that my following code will not be good practice so need to know which way to better to check and easy to maintain?

Here is JSON response:

[
  {
    "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"
      }
    }
  }
]

and here is my python code to check:

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')

Please let me know above code is good practice or not.

5
  • What is wrong with your current snippet? Does it not do what you expect it to do? Commented Mar 29, 2019 at 9:47
  • is there only one object in the json array like your example or there can be multiple objects. Commented Mar 29, 2019 at 9:47
  • PS. The current snippet won't even run for the provided json, since no Messages in response. Commented Mar 29, 2019 at 9:49
  • @DirtyBit yap, that's why is there anyway to do it? Commented Mar 29, 2019 at 9:52
  • @PPShein it is a list so you need to get the 0th element in it and then find the key. Commented Mar 29, 2019 at 9:54

3 Answers 3

4

Another option that you can checkout and one that i actually prefer when i am using JSON data, is to create an object out of the JSON data and use the hasattr method. This will prevent that you start over-using try-except blocks and can also make your code more understandable. An example using your data is the following:

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')

Output:

Received and deleted message: 250e37a8-d779-48a1-9941-84219a82513e
Sign up to request clarification or add additional context in comments.

1 Comment

Could you please explain why MessageId is not interpreted as a dictionary key in your example? Thank you!
2

First as already mentioned you example json does not contain the key Messages. I think you code looks fine. But if the case that you have an json without the key Messages is very rare i would go for a try except block.

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')

This will be much faster for every time you get an "correct" json. But slower when you are getting a json with a missing key. So maybe you need to find out weather the absence of the key occures often or not.

But this depends on the use case. And my answer is only my own opinion and experience from similar use cases

Comments

2

Since the response is a list of dict:

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")

OUTPUT:

250e37a8-d779-48a1-9941-84219a82513e
AQEBjualXJJuhZpg==
1553851566164

EDIT:

Another way could be to check for each key before accessing, i.e (removed the ReceiptHandle elem from the response):

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")

OUTPUT:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.