Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Parse SQS JSON Message with Python

Tags:

I have been trying to wrap my head around this, but I can't seem to get it to work. I can drill down into 'Messages' by specifying it in the sqs polling, but can't get deeper in:

I am retrieving an AWS SQS message:

import boto3

sqs = boto3.client('sqs',
                   aws_access_key_id='<aws-id>',
                   aws_secret_access_key='<aws-key>',
                   region_name='<aws-region>'
                   )

queue_url = '<aws-queue-url'
# Long poll for message on provided SQS queue
response = sqs.receive_message(
    QueueUrl=queue_url,
    MaxNumberOfMessages=1,
    MessageAttributeNames=[
        'Messages'
    ],
    WaitTimeSeconds=20
)

Which returns a JSON response:

{
  'Messages': [
    {
      'MessageId': '37b13967-a92e-4b8b-8aef-32341a8e1e32',
      'ReceiptHandle': 'xyz',
      'MD5OfBody': '081f4bdad6fd3d53c88f165a884a39da',
      'Body': '{"inputIDList":["1234","5678"],"eventID":"9337","scheduleEvent":false,"addToList":true,"listID":"7654","clientID":"123-ABC-456"}'
    }
  ],
  'ResponseMetadata': {
    'RequestId': '79dafe96-04d9-5122-8b2a-a89b79a76a46',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'x-amzn-requestid': '79dafe96-04d9-5122-8b2a-a89b79a76a46',
      'date': 'Tue, 01 Oct 2019 16:13:50 GMT',
      'content-type': 'text/xml',
      'content-length': '4792'
    },
    'RetryAttempts': 0
  }
}

All I need to do here is extract the value for 'Body', but I can't quite drill down far enough without erroring out.

What I would like to return is essentially just this as JSON or a string:

'{"inputIDList":["1234","5678"],"eventID":"9337","scheduleEvent":false,"addToList":true,"listID":"7654","clientID":"123-ABC-456"}'

I'm extremely new at this. Any help would be greatly appreciated!

like image 310
MSB6 Avatar asked Oct 01 '19 20:10

MSB6


2 Answers

You can get the required output using

print (response['Messages'][0]['Body'])
like image 69
matesio Avatar answered Oct 12 '22 22:10

matesio


In adddition to @matesio answer, if you want to store the body of the message as a python dictionary just wrap it with json.loads:

import json
message = json.loads(response['Messages'][0]['Body'])
like image 43
Alex Lopez Avatar answered Oct 12 '22 23:10

Alex Lopez