首页 > 解决方案 > 如何从单引号转换带有双引号的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"

标签: python-3.xamazon-web-servicesamazon-dynamodbboto3

解决方案


您的 JSON 文件内容与您对 DynamoDB 表资源的使用不兼容。您应该使用客户端接口,例如:

boto3.client('dynamodb').put_item(Item)

客户端接口要求您指明属性类型(例如字符串、数字),例如:

'name': { 'S': 'abcd' }

Resource 接口从 Python 原生类型推断数据类型,例如:

'name': 'abcd'

推荐阅读