我正在查看的内容相当于 Document.parse()
在 golang 中,这允许我直接从 json 创建 bson 吗?我不想为编码创建中间 Go 结构
最佳答案
gopkg.in/mgo.v2/bson
包有一个名为 UnmarshalJSON
的函数这正是你想要的。
data
参数应该将 JSON 字符串保存为 []byte
值。
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.
例子:
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)
}
关于mongodb - 如何将 json 字符串编码到 bson 文档以写入 MongoDB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785289/