当我更新一个用于更新 dynamodb 表的结构中的空字符串值时,我卡住了。
目前我有这个结构
type Client struct {
ClientID *string `json:"client_key,omitempty"`
Name *string `json:"client_name,omitempty"`
Address *string `json:"address,omitempty"`
Country *string `json:"country,omitempty"`
City *string `json:"city,omitempty"`
State *string `json:"state,omitempty"`
PostCode *string `json:"post_code,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
}
更新项目时的代码
keyAttr, err := dynamodbattribute.MarshalMap(key)
if err != nil {
return nil, err
}
valAttr, err := dynamodbattribute.MarshalMap(attributes)
if err != nil {
return nil, err
}
keyAttr
将用于 Key
字段,valAttr
将用于 ExpressionAttributeValues
字段。请注意,为了节省空间,我没有包括完整的更新字段功能。但如果您要求,我会这样做。
目前该函数运行良好,除非我用空字符串更新了其中一个字段。例如。 client.Address = aws.String("")
。虽然我可以使用 dynamodb 将我的空字符串转换为 null
,但由于 omitempty
标记,我似乎找不到更新它的方法。
我需要 omitempty 标签来忽略所有 nil
值。但是,我刚刚研究过 omitempty
标记也会省略空字符串值。目前我必须像这样在我的函数中创建一个结构。
type client struct {
Name *string `json:"client_name"`
Address *string `json:"address"`
Country *string `json:"country"`
City *string `json:"city"`
State *string `json:"state"`
PostCode *string `json:"post_code"`
}
但我不喜欢重复事情。所以,问题是:有没有更好的方法来做到这一点?你们如何将结构与 dynamodb 一起使用?
编辑
根据@Peter 的评论,如果 json.Encode()
不是 nil,它似乎会打印空字符串。
{"client_key":"test","username":"test","email":"","first_name":"test","last_name":"","phone":"","title":"","email_verified":false,"phone_verified":false,"updated_at":"2018-12-06T14:04:56.2743841+11:00"
问题似乎出在 dynamodbattribute.MarshalMap
函数中
最佳答案
经过多次尝试,终于搞定了。我没有测试它,所以我不知道它是否有错误。但它现在似乎对我有用。
所以我所做的是首先使用 json.Marshal
对结构进行编码,然后使用 json.Unmarshal
和 map[string]interface{}
。然后,我使用 dynamodbattribute.Marshal
将其转换为 map[string]*AttributeValue
代码如下:
var temp map[string]interface{}
json.Unmarshal(tempStr, &temp)
valAttr, err := dynamodbattribute.MarshalMap(temp)
if err != nil {
return nil, err
}
关于go - 使用结构更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622236/