How to marshal json string to bson document for wr

2020-06-12 02:18发布

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 Go structs for marshaling

标签: mongodb go mgo
1条回答
唯我独甜
2楼-- · 2020-06-12 02:59

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)
}
查看更多
登录 后发表回答