Golang Selecting fields from a struct array

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2013年9月25日 01:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/18988256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定