1

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 {
  println(err)
}

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.

0

1 Answer 1

1

You can ignore struct fields while json.Marshal.

package main

import (
    "encoding/json"
    "fmt"
)

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)

    fmt.Println(string(json))
}

Runnable example in Play Golang: http://play.golang.org/p/AEC_TyXE3B

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.