将特定的JSON字段写入文件

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"}
}