【问题标题】:Golang Maps: How to strip out empty fields automaticallyGolang Maps:如何自动去除空字段
【发布时间】:2016-04-03 10:14:46
【问题描述】:

鉴于以下struct...

package models

import (
    "time"
    "gopkg.in/mgo.v2/bson"
    "github.com/fatih/structs"
)

type User struct {
    Id         bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`
    Name       string        `json:"name,omitempty" bson:"name,omitempty"`
    BirthDate  time.Time     `json:"birth_date,omitempty" bson:"birth_date,omitempty"`
}

...我通过解析这样的 HTTP 请求来填充它:

func (userController *UserController) UpdateUser() echo.HandlerFunc {
    return func(context echo.Context) error {
        user := &models.User{}

        // parse JSON in POST request and fill the User struct
        if err := context.Bind(user); err != nil {
            return err
        }

        // get user id from URL
        query := bson.M{"_id": bson.ObjectIdHex(context.Param("id"))}

        update := bson.M{
            // structs.Map() converts a User struct to a Map[string]interfacce{}
            "$set": structs.Map(user)
        }

        if err := userController.session.DB("test").C("users").Update(query, update); err !=   {
            return err
        }

        return context.JSON(http.StatusOK, user)
    }
}

问题是当我得到这样的更新 JSON 时......

{
    "name": "Bon Scott",
    "birth_date" : "1946-07-09"
}

...structs.Map() 仍然返回一个 Map,其中包含一个空 id,如下所示:

map[%!d(string=Name):%!d(string=Bon Scott) %!d(string=BirthDate):{63108633600 0 10736640} %!d(string=Id):%!d(bson.ObjectId=)]

我会避免像这样逐个字段地手动创建Map

update := bson.M{
    "name": user.Name,
    "birthDate": user.BirthDate,
}

有没有办法自动去除空字段?

【问题讨论】:

    标签: json dictionary go mgo


    【解决方案1】:

    在您的示例中,您已经在bson 中使用了,omitempty 标记。

    基于bson docs

    omitempty 仅包含未设置为零的字段 类型的值或清空切片或映射。

    因此,即使您将地图直接传递给更新调用,也不应该更新空字段。唯一的问题应该是,您应该注意不要给_id 赋予不正确的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多