简体   繁体   中英

Write specific JSON fields to file

I've just started studying Golang and don't understand how to write only specific JSON fields to an output file.

For example I have this struct:

type example struct {
        Ifindex  int    `json:"ifindex"`
        HostID   int    `json:"host_id"`
        Hostname string `json:"hostname"`
        Name     string `json:"name"`
}

My output file should be in the following format:

[{"Ifindex": int, "Hostname": string}, {...}]

How can I do it?

If I understood correctly, you'd like to omit some of the fields when marshalling to JSON. Then use json:"-" as a field tag.

Per the json.Marshal(...) documentation :

As a special case, if the field tag is "-", the field is always omitted.

So you just need to use the tag "-" for any public field that you do not want serialized, for example ( Go Playground ):

type Example struct {
  Ifindex  int    `json:"ifindex"`
  HostID   int    `json:"-"`
  Hostname string `json:"hostname"`
  Name     string `json:"-"`
}

func main() {
  eg := Example{Ifindex: 1, HostID: 2, Hostname: "foo", Name: "bar"}
  bs, err := json.Marshal(&eg)
  if err != nil {
    panic(err)
  }

  fmt.Println(string(bs))
  // {"ifindex":1,"hostname":"foo"}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM