从一种方法我得到的输出低于
{'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'}]}
现在我想从中获取主体的值,所以我在下面使用了
body = event ['Records'] [0] [0] ['body']
但这无法正常工作。您能帮我弄清楚我在做什么错吗?
答案 0 :(得分:1)
我在做什么错了?
Records
键是一个列表,您可以使用该项目的索引号从列表中选择项目。
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"
}
]
}
因此,当您执行json_string['Records'][0]
时,这会选择列表中的第一项,它也是字典:
{
"messageId": "2953dfd5-d848-42b2-a60b-43df00ec8e5f",
"receiptHandle": "AQEBPMr5RbW3T2DG4pAYi+",
"body": "I am still trying",
....}
现在,如果您执行json_string['Records'][0][0]
,则您正在尝试访问字典键,例如列表中的项(使用索引号0),这在语法上是不正确的。如果您想访问'messageId'的值,则可以按名称访问密钥,例如json_string['Records'][0]['messageId']
,或者在您的问题中按如下方式访问“ body”键的值:
`json_string['Records'][0]['body']`
#Output:
I am still trying
答案 1 :(得分:0)
您是否要获得“我还在尝试”?
json_data = {
'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'
}]
}
print (json_data['Records'][0]['body'])
# output
# I am still trying
答案 2 :(得分:0)
如果您尝试获取“ body”元素的值,则看起来应该跳过查找中的第二个[0]
。格式正确,看起来像这样:
{
"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"
}
]
}
因此,要获取“记录”中第一条记录的“正文”字段的值,您应该这样做:
body=event['Records'][0]['body']