如何将以下划线开头的字段编组为JSON [Golang]

Go's encoding/json package has some brilliant JSON marshalling functionality, and for all intents and purposes it's exactly what I need. But the problem arises when I want to try and marshal something I want to insert into a MongoDB instance.

MongoDB understands _id as an indexed identifier, but Go's JSON package only marshals exported fields so MongoDB creates its own ID for the document when I save, which I do not want, and I haven't even begun to test the implications it will have unmarshalling to a struct.

Is there a way to make the JSON marshaller include fields beginning with an underscore without writing a whole new one?

You can easily rename the fields. The Go name should start with an uppercase to be exported, but the json name can be anything compliant with json.

Here is an example borrowed to the encoding/json package documentation:

 package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    type ColorGroup struct {
        ID     int       `json:"_id"`
        Name   string
        Colors []string
    }
    group := ColorGroup{
        ID:     1,
        Name:   "Reds",
        Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    }
    b, err := json.Marshal(group)
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(b)
}