[英]Python dict datatype error while after reading message from AWS SQS and Put it into AWS DynamoDB
My use case is to take a JSON message from SQS body and insert data into DynamoDB Using the lambda function in python. 我的用例是从SQS主体获取JSON消息,然后使用python中的lambda函数将数据插入DynamoDB中。 the issue is I am able to read and print the JSON message from SQS queue into cloud watch log but when I try to insert the same JSON in dynamoDB it gives below Error
问题是我能够从SQS队列读取JSON消息并将其打印到云监视日志中,但是当我尝试在dynamoDB中插入相同的JSON时,它显示以下错误
Invalid type for parameter Item, value: {'name': 2}, type: class 'str', valid types: class 'dict' 参数Item的类型无效,值:{'name':2},类型:class'str',有效类型:class'dict'
Below is the lambda code I am using and an error occurred at line number 12 where I am trying to insert using put_item 以下是我正在使用的Lambda代码,在尝试使用put_item插入的第12行发生了错误
import json
import boto3
dynamodb = boto3.resource('dynamodb')
dynamoTable = dynamodb.Table('message')
def lambda_handler(event, context):
for record in event['Records']:
data1 = record["body"]
jsondata1 = json.loads(data1)
print(jsondata1)
dynamoTable.put_item(Item=jsondata1)
However, it is able to print the SQS JSON to cloud watch log as below 但是,它可以将SQS JSON打印到云监视日志,如下所示
after so many R&D i am able to find the solution is by splitting the string by comma and then recreating an json which will create json of dict data type and not string 经过如此多的研发,我能够找到解决方案的方法是用逗号分割字符串,然后重新创建一个json,它将创建dict数据类型而不是字符串的json
Below is the code for the same solution 以下是相同解决方案的代码
import json
import boto3
import ast
dynamodb = boto3.resource('dynamodb')
dynamoTable = dynamodb.Table('message')
def lambda_handler(event, context):
for record in event['Records']:
data1 = record["body"]
jsondata1 = json.loads(data1)
mess1 = jsondata1["Message"]
id = jsondata1["MessageId"]
jsonmess = json.loads(mess1)
s = jsonmess.replace("{" ,"")
finalstring = s.replace("}" , "")
split = finalstring.split(",")
dict = {'messageID':id}
for x in split:
keyvalue = x.split(":")
print(keyvalue)
dict[keyvalue[0]]=keyvalue[1]
dynamoTable.put_item(Item=dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.