登录
首页 >  Golang >  Go问答

How to marshal json string to bson document for writing to MongoDB?

来源:Golang技术栈

时间:2023-04-26 14:34:37 487浏览 收藏

大家好,我们又见面了啊~本文《How to marshal json string to bson document for writing to MongoDB?》的内容中将会涉及到golang等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

What I am looking is equivalent of [Document.parse()](https://api.mongodb.com/java/3.2/org/bson/Document.html#parse- java.lang.String-)

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

正确答案

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)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表