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

使用lib-dynamodb无法显示嵌套列表问题求助

问题

我有一个DynamoDB表,其中的Item数据如下:

{
    "Item": {
        "myPrimaryKey": {
            "S": "config"
        },
        "mySecondaryKey": {
            "S": "sports"
        },
        "configValues": {
            "SS": [
                "baseball",
                "basketball",
                "football"
            ]
        }
    }
}

使用AWS SDK v3的@aws-sdk/lib-dynamodb编写了以下代码:

const { DynamoDB } = require('@aws-sdk/client-dynamodb');
const client = new DynamoDB({ region: 'us-east-1' });

const { DynamoDBDocument, GetCommand } = require('@aws-sdk/lib-dynamodb');
const ddbDocClient = DynamoDBDocument.from(client);

const params = {
  'TableName': 'mySportBookTable',
  'Key': {
    'myPrimaryKey': 'config',
    'mySecondaryKey': 'sports',
  },
};

const data = await ddbDocClient.send(new GetCommand(params));
console.log('sendDocClientCommand -- Received data: ', JSON.stringify(data));

执行后发现返回的data中configValues显示为空对象{},但AWS CLI执行等效命令能正常获取完整数据:

$ aws dynamodb get-item \
    --table-name "mySportBookTable" \
    --key '{"myPrimaryKey":{"S":"config"},"mySecondaryKey":{"S":"sports"}}'

CLI返回结果:

{
    "Item": {
        "myPrimaryKey": {
            "S": "config"
        },
        "mySecondaryKey": {
            "S": "sports"
        },
        "configValues": {
            "SS": [
                "baseball",
                "basketball",
                "football"
            ]
        }
    }
}

SDK版本为3.454.0,查阅文档得知除非设置ProjectionAttributes否则会返回所有值,但找不到展开嵌套列表的配置方法,求解决。

解决方案

问题根源是DynamoDBDocument客户端的自动类型转换行为:它会将DynamoDB原生格式(如SS字符串集合)自动转换为JavaScript原生数组,但你通过JSON.stringify(data)打印时,可能因为对象结构的展示问题误以为configValues是空对象——实际上它已经被转换为数组了。

直接修改打印代码,访问data.Item下的具体属性即可看到正确数据:

console.log('sendDocClientCommand -- Received configValues: ', data.Item.configValues);
// 预期输出: ["baseball", "basketball", "football"]

如果需要保留DynamoDB原生类型格式(不自动转换),可以在创建DynamoDBDocument客户端时配置序列化选项:

const ddbDocClient = DynamoDBDocument.from(client, {
  unmarshallOptions: {
    // 关闭自动类型转换,保留DynamoDB原生格式
    convertEmptyValues: false,
  },
});

推荐使用默认的自动转换行为,它让你直接操作JavaScript原生类型,无需处理DynamoDB的S/SS等类型标识。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:35:02