我从dynamodb中读取了一些数据。这就是我得到的
{
Item: {
rating: {
N: "6"
},
pk: {
S: "artist-1"
},
gender: {
S: "woman"
},
sk: {
S: "Alexandra A"
}
}
}
现在,我有一个看起来像这样的结构:
type Artist struct {
ArtistID string `json:"id"`
Gender string `json:"gender"`
Name string `json:"name"`
Rating float64 `json:"rating"`
}
现在我做
artist := model.Artist{}
err = dynamodbattribute.UnmarshalMap(result.Item, &artist)
现在我可以访问例如带有
artist.gender
的性别。所以这很好,但是我无法对ArtistId执行此操作,因为在我的dynamodb中将其称为pk,并且将'id'用作结构。有什么干净的方法可以解决这个问题?我不想在结构中将“id”替换为“pk”。
最佳答案
UnmarshalMap()
不支持任何给定标签Unmarshal。如果您不想在结构中将'id'更改为'pk',则必须先在pk
键中设置id
的值,然后再在 map 中手动设置UnmarshalMap
。
func UnmarshalMap(m map[string]*dynamodb.AttributeValue, out interface{}) error {
m["id"] = m["pk"]
dynamodbattribute.UnmarshalMap(m, out)
}
最好为这种特殊情况的调整创建自己的通用Unmarshal函数,然后在内部调用
UnmarshalMap()
。artist := model.Artist{}
err = UnmarshalMap(result.Item, &artist)
关于go - 将DynamoDBAttributeValues解码为具有不同属性的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61032869/