douzhuo6931
2016-09-30 06:45
浏览 562

如何在Golang中将json字符串编组到bson文档以写入MongoDB?

What I am looking is equivalent of Document.parse()

in golang, that allows me create bson from json directly? I do not want to create intermediate golang structs for marshaling

图片转代码服务由CSDN问答提供 功能建议

我正在寻找的内容等同于 Document.parse()

我直接从json创建bson吗? 我不想创建用于封送处理的中间golang结构

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyin8623 2016-09-30 09:52
    已采纳

    The gopkg.in/mgo.v2/bson package has a function called UnmarshalJSON which does exactly what you want.

    The data parameter should hold you JSON string as []byte value.

     func UnmarshalJSON(data []byte, value interface{}) error
    

    UnmarshalJSON unmarshals a JSON value that may hold non-standard syntax as defined in BSON's extended JSON specification.

    Example:

    var bdoc interface{}
    err = bson.UnmarshalJSON([]byte(`{"id": 1,"name": "A green door","price": 12.50,"tags": ["home", "green"]}`),&bdoc)
    if err != nil {
        panic(err)
    }
    err = c.Insert(&bdoc)
    
    if err != nil {
        panic(err)
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题