lambda函数正在从SQS接收以下消息
"Records": [
{
"messageId": "a91c1641-fb7e-4ce5-88ad-2dd180aaada6",
"receiptHandle": "AQEBngcKiVX9S0IjX6SfCm5VAtaDbSxznYLDMMoN2J5pq+uzVLdyzsaBVwXVjOE94dBnzAqkbI2II8RvfIfEeQCwp/8MxV5OLJXEQiBhpm2QwCXlUy+1ludjUbKRXT6pBux0eqjuVDk4I/vQ59m3D+ut2mafo2wgEZtUqT28P5DVgpeCgwFmuHcSRoc/vjcj/5rBDSJ6Mk4T+XTnnPMkZXOY0Nl9+XWzXJe3eX+DJC7vn6Vi6wEMk84nhbjn+CdL/TpHFtA6qCFE03XEJnRQeZCf69sqbpGq+ecIKI+bxb5DMDOTIin+ugb1oqpvfhySkB9nWodYOv+P6ANeLJSm4kBRvsSriDcP9uO/whyQGUMZC1v0Kx0CFVqtVmg2fIoj5R8k3f7QU9zpTKrJO5Bn/K6BwA==",
"body": "[\n {\n \"year\": 2013,\n \"title\": \"Rush\",\n \"info\": {\n \"directors\": [\"Ron Howard\"],\n \"release_date\": \"2013-09-02T00:00:00Z\",\n \"rating\": 8.3,\n \"genres\": [\n \"Action\",\n \"Biography\",\n \"Drama\",\n \"Sport\"\n ],\n \"image_url\": \"http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg\",\n \"plot\": \"A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.\",\n \"rank\": 2,\n \"running_time_secs\": 7380,\n \"actors\": [\n \"Daniel Bruhl\",\n \"Chris Hemsworth\",\n \"Olivia Wilde\"\n ]\n }\n }\n]",
"attributes": {
"ApproximateReceiveCount": "1",
"SentTimestamp": "1604156768953",
"SenderId": "983336180496",
"ApproximateFirstReceiveTimestamp": "1604156768958"
},
"messageAttributes": {},
"md5OfBody": "3d249c6c5e1b6cffc0f7af7101f3ea40",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-east-1:983336180496:Parse-SQS-Msg",
"awsRegion": "us-east-1"
}
]
现在在正文部分,我想提取诸如“年”,“标题”和“评分”之类的详细信息。如何提取不同变量中的这些详细信息,以便可以据此编写逻辑?我要提取的详细信息是年份,标题,流派和等级:
"body": "[
{
"year": 2013,
"title": "Rush",
"info": {
"directors": ["Ron Howard"],
"release_date": "2013-09-02T00:00:00Z",
"rating": 8.3,
"genres": [
"Action",
"Biography",
"Drama",
"Sport"
],
"image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
"plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
"rank": 2,
"running_time_secs": 7380,
"actors": [
"Daniel Bruhl",
"Chris Hemsworth",
"Olivia Wilde"
]
}
}
]
代码段如下:
from __future__ import print_function
from pprint import pprint
from botocore.vendored import requests
import boto3
import json
dynamodb = boto3.resource('dynamodb')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
for record in event['Records']:
print ("test")
year_e = record['body'][0]
print(year_e)
payload=record["body"]
print(str(payload))
我尝试了几种来自网络的排列组合,但没有任何帮助。我是Python的新手,因此非常感谢您的帮助。
答案 0 :(得分:0)
问题是body
字段包含JSON,但是它是文本格式。您需要使用以下命令将其转换为Python对象:
body = json.loads(record['body'])
然后您可以将内容引用为字典:
for film in body:
print(film['title'], film['year'], film['info']['rating'])