代码之家  ›  专栏  ›  技术社区  ›  kkesley

使用结构更新值

  •  0
  • kkesley  · 技术社区  · 6 年前

    在更新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 价值观。然而,我只是研究了 省略 标记还省略空字符串值。目前我必须在函数中创建这样的结构。

    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() 如果不是零,则打印空字符串。

    {"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 功能

    1 回复  |  直到 6 年前
        1
  •  0
  •   kkesley    6 年前

    经过几次试验,我终于得到了它。我没有测试它,所以我不知道它是不是马车。但它现在似乎对我有用。

    所以我所做的就是用 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
    }