2013-09-24 17:30
浏览 115


I get an array of all the users with an attribute ID in their document:

Users := []backend.User{}

err := Collection.Find(bson.M{"channel_id": bson.ObjectIdHex(chId)}).All(&Users)
if err != nil {

Which I want to send as a JSON response back to the browser/client. However, the User struct contains things like IDs and Hahsed Passwords which i don't want to send back!

I was looking at something like using the reflect package to select the fields of the struct and then putting them into a map[string]interface{} but im not sure how to do it with an array of users.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsb12300 2013-09-24 18:26

    You can ignore struct fields while json.Marshal.

    package main
    import (
    type User struct {
        Id   int    `json:"-"`
        Name string `json:"name"`
    type Users []*User
    func main() {
        user := &Users{
            &User{1, "Max"},
            &User{2, "Alice"},
            &User{3, "Dan"},
        json, _ := json.Marshal(user)

    Runnable example in Play Golang:

    There is a very useful part about using the tags in the doc. Same for XML, but it's more complicated for obvious reasons.

    解决 无用
    打赏 举报

相关推荐 更多相似问题