douzhuo6931 2016-09-30 06:45
浏览 1164
已采纳

如何在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

  • 写回答

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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题