Reputation: 466
From one of the method i am getting below output
{'Records': [{'messageId': '2953dfd5-d848-42b2-a60b-43df00ec8e5f',
'receiptHandle': 'AQEBPMr5RbW3T2DG4pAYi+', 'body':
'I am still trying', 'attributes': {'ApproximateReceiveCount': '1',
'SentTimestamp': '1552073955807', 'SenderId': '944198216610',
'ApproximateFirstReceiveTimestamp': '1552073955816'},
'messageAttributes': {}, 'md5OfBody':
'2111a742ddbdac2d862fa6a204f7dc85', 'eventSource': 'aws:sqs',
'eventSourceARN': 'arn:aws:sqs:us-east-
1:944198216610:LambadaQueue', 'awsRegion': 'us-east-1'}]}
Now i want to fetch the value of body from this so i have used below
body=event['Records'][0][0]['body']
But this is not working.Can you please help me figure out what wrong i am doing?
Upvotes: 0
Views: 85
Reputation: 5463
What am I doing wrong?
The Records
key is a list and you can select items from a list using the index number for that item.
json_string = {
"Records": [
{
"messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
"receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
"body": "I am still trying",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1552073955807",
"SenderId": "944198216610",
"ApproximateFirstReceiveTimestamp": "1552073955816"
},
"messageAttributes": { },
"md5OfBody": "2111a742ddbdac2d862fa6a204f7dc85",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-1:944198216610: LambadaQueue",
"awsRegion": "us-east-1"
}
]
}
So, when you do json_string['Records'][0]
, this selects the first item in the list which is again a dictionary:
{
"messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
"receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
"body": "I am still trying",
....}
Now if you do json_string['Records'][0][0]
, you are trying to access a dictionary key like an item in a list(using index number 0) which is syntacticaly incorrect. You can access the key by name such as json_string['Records'][0]['messageId']
if you want to access the value for 'messageId', or as in your question, the "body" key's value like this:
`json_string['Records'][0]['body']`
#Output:
I am still trying
Upvotes: 1
Reputation: 614
If you're attempting to get the value of the "body" element, it looks like you should just skip the second [0]
in your lookup. Properly formatted, it looks like this:
{
"Records": [
{
"messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
"receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
"body": "I am still trying",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1552073955807",
"SenderId": "944198216610",
"ApproximateFirstReceiveTimestamp": "1552073955816"
},
"messageAttributes": { },
"md5OfBody": "2111a742ddbdac2d862fa6a204f7dc85",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-1:944198216610: LambadaQueue",
"awsRegion": "us-east-1"
}
]
}
So, to get the value of the field "body" for the first record in "Records", it looks like you should do:
body=event['Records'][0]['body']
Upvotes: 0