DVA-C02 Question 33
Single answerYou are developing an AWS Lambda function that processes events from an Amazon S3 bucket. The function needs to parse the S3 event JSON object and retrieve the bucket name and object key of the uploaded file. Which of the following code snippets correctly extracts these details from the event object passed to the Lambda function?
- A
bucket_name = event['Records'][0]['s3']['bucket']['name']; object_key = event['Records'][0]['s3']['object']['key']
- B
bucket_name = event['s3']['bucket']['name']; object_key = event['s3']['object']['key']
- C
bucket_name = event['Records'][0]['bucket']['name']; object_key = event['Records'][0]['object']['key']
- D
bucket_name = event['detail']['bucket']['name']; object_key = event['detail']['object']['key']
Show answer and explanation
Correct answer: A
Explanation
When an AWS Lambda function is triggered by an S3 event, the event object contains a 'Records' array that holds details of one or more events. The bucket name and object key can be accessed through the 's3' key inside the relevant record. Understanding the structure of the event JSON is critical for correctly extracting the required information.
- A. Correct.
This is the correct way to parse the S3 event structure provided to an AWS Lambda function triggered by S3. The 'Records' array holds the event details for each object, and the 's3' key contains bucket and object metadata.
- B. Incorrect.
This option is incorrect because it does not include the 'Records' key, which is required to access the event details.
- C. Incorrect.
This option is incorrect because it omits the 's3' key, which is necessary to access the bucket and object information.
- D. Incorrect.
This option is incorrect because the 'detail' key is not part of the S3 event structure; it is typically used for EventBridge events.