python-3.x - 如何从单引号转换带有双引号的python字典
问题描述
我正在尝试通过用 python 编写的 lambda 函数执行 put_item dynamodb 操作。我的项目看起来像 -
{'Item': {'AccNum': {'S': 'ACC2000000017201'}, 'AdjustmentId': {'N': '0'}}}
Type - <class 'dict'>
但 dynamodb 期望项目以字典格式位于双引号内。我尝试使用json.dumps并将每个键转换为双引号,但它将项目转换为字符串类型而不是字典。我不能使用字符串类型,因为 dynamodb 会因类型不匹配而引发错误。谁能帮助我在这种情况下如何获取带有双引号的字典项?
预期 o/p :
{"Item": {"AccNum": {"S": "ACC2000000017201"}, "AdjustmentId": {"N": "0"}}}
Type - <class 'dict'>
代码 -
import json
import gzip
import boto3
import io
dynamodb = boto3.resource('dynamodb')
# Event holds the individual s3 file with backup data
def lambda_handler(event, context):
table = dynamodb.Table('mahbis01-AccountService-LedgerSummary-Duplicate')
# Retrieve the bucket name and file name from event
bucket = event['Records'][0]['s3']['bucket']['name']
json_file_name = event['Records'][0]['s3']['object']['key']
s3 = boto3.resource('s3')
json_object = s3.Object(bucket, json_file_name)
buf = io.BytesIO(json_object.get()['Body'].read())
for line in gzip.GzipFile(fileobj=buf):
line = json.loads(line)
table.put_item(Item=line)
"errorMessage": "An error occurred (ValidationException) when calling the PutItem operation: One or more parameter values were invalid: Missing the key AccNum in the item"
解决方案
您的 JSON 文件内容与您对 DynamoDB 表资源的使用不兼容。您应该使用客户端接口,例如:
boto3.client('dynamodb').put_item(Item)
客户端接口要求您指明属性类型(例如字符串、数字),例如:
'name': { 'S': 'abcd' }
Resource 接口从 Python 原生类型推断数据类型,例如:
'name': 'abcd'
推荐阅读
- java - 本地主机的 InetSocketAddress
- php - PHP 获取多个数据
- php - get_headers 不同的结果 xampp localhost
- angular - 来自 FormBuilder 的角度转换。样式到 FormGroup。如何创建Formarray?
- ruby-on-rails - 如何通过 Ruby on Rails 中的 API GET 请求访问(并保存到我的数据库)JSON 数组中的嵌套对象/属性?
- jenkins - 将构建信息发布到来自 jenkins 的通用人工仓库
- scala - Scala Play 2.8 Framework:分割路由文件,前缀包含动态部分
- haskell - Haskell如何将文件分成多个文件
- javascript - 从 PDF 中提取 PDF 表单元数据
- quarkus - Quarkus Panache 在 1.8 之后无法使用 persistence.xml