如何编组json字符串到golang中的bson文档以写入MongoDB? [英] How to marshal json string to bson document in golang for writing to MongoDB?

查看:256
本文介绍了如何编组json字符串到golang中的bson文档以写入MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看的相当于 Document.parse()



在golang中,允许我直接从json创建bson?我不想创建用于编组的中间golang结构 解决方案

gopkg.in/mgo.v2/bson 软件包有一个叫做 UnmarshalJSON ,它的确如此
$ b

data 参数应该将JSON字符串保存为 [] byte value。

func UnmarshalJSON(data [] byte,value interface { })错误




UnmarshalJSON取消编组可能存在非标准的JSON值语法定义在BSON的扩展JSON规范中。

示例:

  var bdoc interface {} 
err = bson.UnmarshalJSON([] byte(`{id:1,name:绿色的门,价格:12.50 ,标签:[ho如果错误!=零{
恐慌(错误)
}
err = c.Insert(& bdoc)
, bdoc)

如果err!= nil {
panic(err)
}


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

解决方案

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

这篇关于如何编组json字符串到golang中的bson文档以写入MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆