dongyi5570 2015-05-15 15:34
浏览 247
已采纳

如何将以下划线开头的字段编组为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 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘