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

如何用Python删除DynamoDB中含空格键的嵌套JSON属性

解决方案

你当前代码的问题是delete_item会直接删除整行对应联赛+球队的完整数据,而非仅移除Players字段下的指定球员。正确实现需要使用update_item结合表达式属性名来处理带空格的球员名:

  • 核心逻辑是通过REMOVE指令删除Players Map结构下的指定键
  • 用ExpressionAttributeNames做占位符,规避球员名带空格导致的表达式语法错误
  • 可选增加条件表达式,仅当目标球员存在时才执行删除操作,避免无意义写入

修改后的完整代码如下:

def lambda_handler(event, context):
    newLeague = None
    newTeam = None
    newPlayer = None
    statusCode = 200

    if checkKey(event, 'League'):
        newLeague = event['League']
    
    if checkKey(event, 'Team'):
        newTeam = event['Team']
    
    if checkKey(event, 'Player'):
        newPlayer = event['Player']

    if newLeague and newTeam and newPlayer:
        response = table.update_item(
            Key={
                'League': newLeague,
                'Team': newTeam
            },
            # 用#player占位符指代带空格的球员名
            UpdateExpression="REMOVE Players.#player",
            ExpressionAttributeNames={
                "#player": newPlayer
            },
            # 可选:仅当球员存在时执行删除
            ConditionExpression="attribute_exists(Players.#player)"
        )

注:如果你的Players字段存储的是JSON字符串而非DynamoDB原生Map类型,需要先调用get_item读取数据,反序列化JSON后删除对应键,再序列化写回数据库即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 00:24:03