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

请求:AWS API Gateway动态转换DynamoDB返回JSON格式

动态处理DynamoDB到简洁JSON的映射模板方案

完全懂你的痛点——硬编码每个字段不仅繁琐,还没法应对字段增减或类型变化的场景。我们可以利用API Gateway映射模板使用的Velocity模板语言特性,动态遍历所有字段并自动剥离DynamoDB的类型标识。

完整的动态映射模板

#set($inputRoot = $input.path('$'))
[
#foreach($elem in $inputRoot.Items)
  {
  #set($firstField = true)
  #foreach($key in $elem.keySet())
    #set($value = $elem.get($key))
    #foreach($type in $value.keySet())
      #if(!$firstField),#end
      "$key": 
      #if($type == "S" || $type == "BOOL")
        "$value.get($type)"
      #elseif($type == "N")
        $value.get($type)
      #elseif($type == "L")
        [
        #set($firstListElem = true)
        #foreach($listItem in $value.get($type))
          #foreach($listType in $listItem.keySet())
            #if(!$firstListElem),#end
            #if($listType == "S" || $listType == "BOOL")
              "$listItem.get($listType)"
            #elseif($listType == "N")
              $listItem.get($listType)
            #end
          #end
          #set($firstListElem = false)
        #end
        ]
      #else
        "$value.get($type)"
      #end
      #set($firstField = false)
    #end
  #endforeach
  }#if($foreach.hasNext),#end
#endforeach
]

关键逻辑拆解

  1. 遍历Items数组:从DynamoDB返回的根节点中提取Items数组,逐个处理每一条数据
  2. 动态获取字段名:通过$elem.keySet()自动获取当前条目的所有字段,无需提前声明任何固定字段
  3. 适配多种数据类型:
    • 字符串(S)、布尔值(BOOL):添加双引号,符合JSON字符串格式要求
    • 数字(N):直接输出数值(不加引号),保证JSON的数字类型正确性
    • 列表(L):递归遍历列表内的元素,保持数组结构并处理内部的类型标识
    • 其他类型(如二进制B、嵌套对象M等):默认转为字符串输出,你可以根据需求扩展对应的处理分支

效果验证

针对你提供的DynamoDB返回示例:

{ "Count": 10, "Items": [ { "acc_secret": { "S": "12345" }, "acc_apikey": { "S": "abcde" }, "login": { "S": "user" } } ] }

使用该模板后会输出你期望的简洁格式:

[ { "acc_secret": "12345", "acc_apikey": "abcde", "login": "user" } ]

实用提示

  • 如果你的数据包含嵌套对象(M类型),可以在模板中添加对应的处理分支,逻辑和处理顶级条目类似
  • 确保在API Gateway的Integration Response中,为application/json类型配置该映射模板
  • 可以通过API Gateway的测试功能快速验证转换结果,按需调整模板适配你的特定数据类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:33:09