如何将json字符串编组到bson文档以写入MongoDB? [英] How to marshal json string to bson document for writing to MongoDB?
本文介绍了如何将json字符串编组到bson文档以写入MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
What I am looking is equivalent of Document.parse()
在golang中,这允许我直接从json创建bson吗?我不想创建用于编组的中间Go结构
in golang, that allows me create bson from json directly? I do not want to create intermediate Go structs for marshaling
推荐答案
gopkg.in/mgo.v2/bson
软件包具有一个名为 UnmarshalJSON
的函数你想要什么.
The gopkg.in/mgo.v2/bson
package has a function called UnmarshalJSON
which does exactly what you want.
data
参数应将JSON字符串保存为[]byte
值.
The data
parameter should hold you JSON string as []byte
value.
func UnmarshalJSON(data []byte, value interface{}) error
UnmarshalJSON解组一个可能包含BSON扩展JSON规范中定义的非标准语法的JSON值.
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)
}
这篇关于如何将json字符串编组到bson文档以写入MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文