英文:
Golang Selecting fields from a struct array
问题
我得到了一个包含具有属性ID的用户文档的数组:
Users := []backend.User{}
err := Collection.Find(bson.M{"channel_id": bson.ObjectIdHex(chId)}).All(&Users)
if err != nil {
println(err)
}
我想将其作为JSON响应发送回浏览器/客户端。然而,User结构包含诸如ID和哈希密码之类的信息,我不想发送回去!
我在考虑使用reflect包来选择结构体的字段,然后将它们放入map[string]interface{}中,但我不确定如何处理用户数组。
英文:
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.
答案1
得分: 1
你可以在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))
}
在Play Golang中可以运行的示例:http://play.golang.org/p/AEC_TyXE3B
在文档中有关于使用标签的非常有用的部分。对于XML也是一样,但由于明显的原因,它更加复杂。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论