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

将DynamoDB JSON转换为AttributeValue、Go对象或普通JSON

实现DynamoDB Object到Go结构体/JSON对象的转换

方法一:通过AWS SDK映射到Go结构体

AWS SDK for Go v2提供了原生工具,可直接将dynamodb.AttributeValue映射到自定义Go结构体,无需手动处理S/N这类类型标识。

操作步骤:

  1. 定义与DynamoDB字段对应的Go结构体,用dynamodbav标签指定字段映射关系。
  2. 将原始JSON字符串解析为包含Item的临时结构,提取出map[string]types.AttributeValue类型的Item数据。
  3. 使用SDK的attributevalue.UnmarshalMap完成映射。

代码示例:

package main

import (
	"encoding/json"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// 自定义目标结构体
type Item struct {
	Id         string `dynamodbav:"Id"`
	CreateTime int64  `dynamodbav:"CreateTime"`
}

func main() {
	// 原始DynamoDB JSON字符串
	ddbJSON := `{
		"Item": {
			"Id": {
				"S": "db31"
			},
			"CreateTime": {
				"N": "1647882237618915000"
			}
		}
	}`

	// 解析JSON提取Item部分
	var temp struct {
		Item map[string]types.AttributeValue `json:"Item"`
	}
	if err := json.Unmarshal([]byte(ddbJSON), &temp); err != nil {
		panic(err)
	}

	// 映射到自定义结构体
	var item Item
	if err := attributevalue.UnmarshalMap(temp.Item, &item); err != nil {
		panic(err)
	}

	fmt.Printf("映射后的结构体:%+v\n", item)
}

方法二:直接转换为简单Go JSON对象

如果不想依赖AWS SDK,可以手动解析DynamoDB的类型标识,将其转换为原生Go类型的JSON结构。

代码示例:

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
)

// 定义DynamoDB字段的类型结构(可扩展支持B/BOOL/L/M等类型)
type DDBField struct {
	S *string `json:"S"`
	N *string `json:"N"`
}

func main() {
	ddbJSON := `{
		"Item": {
			"Id": {
				"S": "db31"
			},
			"CreateTime": {
				"N": "1647882237618915000"
			}
		}
	}`

	// 解析原始JSON到临时结构
	var temp struct {
		Item map[string]DDBField `json:"Item"`
	}
	if err := json.Unmarshal([]byte(ddbJSON), &temp); err != nil {
		panic(err)
	}

	// 转换为原生Go类型的map
	simpleMap := make(map[string]interface{})
	for key, field := range temp.Item {
		if field.S != nil {
			simpleMap[key] = *field.S
		} else if field.N != nil {
			num, err := strconv.ParseInt(*field.N, 10, 64)
			if err != nil {
				panic(err)
			}
			simpleMap[key] = num
		}
	}

	// 输出转换后的JSON字符串
	jsonBytes, err := json.MarshalIndent(simpleMap, "", "  ")
	if err != nil {
		panic(err)
	}
	fmt.Println("转换后的简单JSON对象:")
	fmt.Println(string(jsonBytes))
}

输出结果:

{
  "CreateTime": 1647882237618915000,
  "Id": "db31"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:21:07