'How to get the object details from SQS body?

I have the following script:

import boto3

# Get the service resource
sqs = boto3.resource('sqs')

# Get the queue
queue = sqs.get_queue_by_name(QueueName='')

for message in queue.receive_messages():
    print(message.body)

    # Let the queue know that the message is processed
    message.delete()

It returns the following as the message's body:

{"Records":[{"eventVersion":"2.0","eventSource":"aws:s3","awsRegion":"us-west-2","eventTime":"2017-03-03T11:06:25.329Z","eventName":"ObjectCreated:Copy","userIdentity":{"principalId":"AWS:<id>:<lambda_name>"},"requestParameters":{"sourceIPAddress":"54.186.104.49"},"responseElements":{"x-amz-request-id":"8577BEEB91F199BF","x-amz-id-2":"<>="},"s3":{"s3SchemaVersion":"1.0","configurationId":"PutFromSisterBucket","bucket":{"name":"<bucket_name>","ownerIdentity":{"principalId":"<>"},"arn":"arn:aws:s3:::<bucket_nmae>"},"object":{"key":"<object_key>","size":1990,"versionId":"anHi0ukirRiApp4jyoSTz2oVGOejR6tJ","sequencer":"0058B94E3141A83718"}}}]}

How do I get the value of the "key" inside the "object"?

Currently, the entire result is a string. Is there any way I can do without string indexing or regex match?



Solution 1:[1]

If the variable message is string you need to load it with json.loads, to parse to dict type in python, so you can use it like a json:

import json

for message in queue.receive_messages():
    message_dict = json.loads(message)
    record = message_dict["Records"][0]
    content = record["s3"]["object"]["key"]
    print(content)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Márcio Ramos