go - 如何将 JSON 解码为 dynamodb.AttributeValue?

标签 go amazon-dynamodb

例如,在输入时:

[
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A+"
                }
            }
        },
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A++"
                }
            }
        },
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A+++"
                }
            }
        }
    ]

而不是 Capacity , Energy我可以得到其他 key 。我没有找到任何方法可以从此类输入中进行准备 dynamodb.AttributeValue适用于UpdateItem .

我试图解码为 []map[string]interface{}然后转换为 dynamodb.AttributeValue .

最佳答案

解码到 []map[string]map[string]*dynamodb.AttributeValue{}然后 CapacityEnergy key 解码为 dynamodb.AttributeValue .

因此,您可以使用 map[string]*dynamodb.AttributeValue 类型的外部映射值如ExpressionAttributeValuesUpdateItemInputUpdateItem

package main

import (
    "encoding/json"
    "fmt"

    "github.com/aws/aws-sdk-go/service/dynamodb"
)
func main() {
    data := []byte(`[
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A+"
                }
            }
        },
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A++"
                }
            }
        },
        {
            "M": {
                "Capacity": {
                    "S": "7"
                },
                "Energy": {
                    "S": "A+++"
                }
            }
        }
    ]`)

    d := []map[string]map[string]*dynamodb.AttributeValue{}
    json.Unmarshal(data, &d)
    for _, mp := range d {
        expressionAttributeValues := mp["M"]
        // you can use expressionAttributeValues as ExpressionAttributeValues in UpdateItemInput to UpdateItem
        capacity := expressionAttributeValues["Capacity"]
        energy := expressionAttributeValues["Energy"]
        fmt.Printf("%+v", capacity)
        fmt.Printf("%+v", energy)
    }
}

关于go - 如何将 JSON 解码为 dynamodb.AttributeValue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61092035/

相关文章:

import - 从父目录相对导入

json - golang yaml 支持 jsonlines

amazon-web-services - 更新 dynamodb 中的集合线程安全吗?

amazon-web-services - 使用CloudFormation创建本地二级索引

php - 如何使用全局二级索引创建表 dynamodb

java - 如何使用 EasyMock 模拟 DynamoDB 的 ItemCollection<QueryResult>?

go - 为什么json值是空的

http - 是否可以限制每秒运行多少个 goroutines?

templates - 在 Go 模板中迭代一系列整数

excel - 是否可以从 Excel 文件导入 AWS DynamoDB 中的数据?