You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用boto3更新DynamoDB:如何将str类型转为dict类型?

问题根源

你的代码里多次使用json.dumps()将Python对象转为JSON字符串,最终传给DynamoDB的final是字符串类型,但DynamoDB要求传入Python原生数据类型(如dict、list),而非序列化后的JSON字符串。同时代码中存在大量无意义的序列化/反序列化操作,完全没必要。

修正方案(存储用户列表)

如果你的users字段在DynamoDB中定义为List类型(用于存储多个用户),可以用以下代码直接操作Python原生列表:

import boto3

def update_record_Dynamo(
    company_name,
    first_name,
    last_name,
    email,
    status,
    phone):
    
    table_name = "cpe-uat-ddb-cem-newpro"
    table = boto3.resource("dynamodb").Table(table_name)
    
    # 获取现有记录,处理公司不存在的边界情况
    response = table.get_item(Key={'company': company_name})
    if 'Item' not in response:
        users_list = []
    else:
        existing_users = response['Item']['users']
        # 统一转为列表格式(兼容原字段是单个用户dict的情况)
        users_list = [existing_users] if isinstance(existing_users, dict) else existing_users.copy()
    
    # 构造新用户字典
    new_user = {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "phone": phone,
        "status": status
    }
    
    # 追加新用户到列表
    users_list.append(new_user)
    
    # 直接传入Python列表更新DynamoDB
    update_record_response = table.update_item(
        Key={'company': company_name},
        AttributeUpdates={
            'users': users_list,
        },
    )
    
    return update_record_response
备选方案(存储用户字典)

如果你的users字段定义为Dict类型(以邮箱为唯一键存储用户),可以用以下逻辑:

import boto3

def update_record_Dynamo(
    company_name,
    first_name,
    last_name,
    email,
    status,
    phone):
    
    table_name = "cpe-uat-ddb-cem-newpro"
    table = boto3.resource("dynamodb").Table(table_name)
    
    response = table.get_item(Key={'company': company_name})
    if 'Item' not in response:
        users_dict = {}
    else:
        users_dict = response['Item']['users'].copy()
    
    new_user = {
        "first_name": first_name,
        "last_name": last_name,
        "email": email,
        "phone": phone,
        "status": status
    }
    
    # 用邮箱作为键更新/添加用户
    users_dict[email] = new_user
    
    update_record_response = table.update_item(
        Key={'company': company_name},
        AttributeUpdates={
            'users': users_dict,
        },
    )
    
    return update_record_response

内容的提问来源于stack exchange,提问作者bhargav patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:15:45