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

AWS DynamoDB AttributeValue.wrap()转字符串数组为SS而非L类型的问题

问题:AWS DynamoDB AttributeValue.wrap() 将字符串数组转为SS类型,需适配App Sync的L格式

使用AttributeValue.wrap()处理包含字符串数组的对象时,数组会被自动转换为DynamoDB的**String Set(SS)类型,但业务需要输出符合App Sync要求的List(L)**格式——每个元素需是单独的字符串类型(S)对象。

原代码

var temp = {
    code:"A",
    guids: [
      "07088ea1-cb53-4bd3-b7a7-2a1fdf1e99ca",
      "30dce880-0b00-4682-b612-4b54dbf7caef",
    ]
   }
  
var newRecord = dbDataTypes.AttributeValue.wrap(temp);

当前输出(不符合需求)

guids: {
    SS: [
      '07088ea1-cb53-4bd3-b7a7-2a1fdf1e99ca',
      '30dce880-0b00-4682-b612-4b54dbf7caef'
    ]
}

期望的App Sync兼容格式

"Guids": {
    "L": [
     {
      "S": "1dc8a478-d2af-4d84-ba57-4b1be4fb3c7c"
     },
     {
      "S": "dbe47150-1940-44cf-a264-421e63f0aacd"
     }
    ]
}

解决方案

AttributeValue.wrap()会自动推断数组类型为集合(Set),要生成List类型,需手动构造AttributeValue结构,而非直接传入原生数组:

方案1:手动构造List结构

直接在原对象中定义L类型的结构,每个元素用S包裹:

var temp = {
    code: "A",
    guids: {
        L: [
            { S: "07088ea1-cb53-4bd3-b7a7-2a1fdf1e99ca" },
            { S: "30dce880-0b00-4682-b612-4b54dbf7caef" }
        ]
    }
};

var newRecord = dbDataTypes.AttributeValue.wrap(temp);

方案2:工具函数动态转换

如果需要批量处理数组,可封装工具函数统一转换:

function convertArrayToDynamoList(strArray) {
    return {
        L: strArray.map(item => ({ S: item }))
    };
}

var temp = {
    code: "A",
    guids: convertArrayToDynamoList([
        "07088ea1-cb53-4bd3-b7a7-2a1fdf1e99ca",
        "30dce880-0b00-4682-b612-4b54dbf7caef"
    ])
};

var newRecord = dbDataTypes.AttributeValue.wrap(temp);

以上两种方式都能让guids字段以L类型输出,完全匹配App Sync的解析要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:03:19