dongyi5570
2015-05-15 15:34 阅读 109

如何将以下划线开头的字段编组为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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongyou9373 dongyou9373 2015-05-15 16:44

    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)
    }
    
    点赞 评论 复制链接分享

相关推荐