is there a way to go straight from an mgo result to a JSON byte array without having to serialize to a slice of structs first?
Decode the result to an interface{}
. Encode the interface{}
as JSON.
var v interface{}
if err := c.Find(query).One(&v); err != nil {
// handle error
}
p, err := json.Marshal(v)
if err != nil {
// handle error
}
// p is []byte containing the JSON
The method One() according with the documentation: executes the query and unmarshals the first obtained document into the result argument, so it's doing the Marshal anyways, but we can "trick" it using the type json.RawMessage that is just a slice of bytes and it's in the std library.
var result json.RawMessage
if err := c.Find(query).One(&result); err != nil { ... }
There's a full example here about RawMessage.