使用bson.Raw从查询中返回完整的JSON。

huangapple go评论93阅读模式
英文:

MongoDB Return entire JSON from query using bson.Raw

问题

我正在尝试搜索这个文档:

"meta": {
	"pageId": "...",
	"userId": "...",
	"ver": "0",
},
"dialog": {
 ...
}

并将整个"dialog"作为JSON获取,所以我创建了这个结构体:

type Dialog struct {
    Dialog bson.Raw `json:"dialog" bson:"dialog"`
}

然后我这样查询文档:

dialog := Dialog{}
query := c.Find(locate).One(&dialog)

当我打印dialog时,我得到一堆数字,我相信这些是查询结果的原始字节。

问题是:如何将其解组为JSON对象?

我找到的唯一相关信息是 https://stackoverflow.com/questions/25276884/marshal-into-a-bson-raw(它没有解释如何解组为JSON)。

更新

根据 https://stackoverflow.com/questions/39785289/how-to-marshal-json-string-to-bson-document-in-golang-for-writing-to-mongodb,我做了以下操作:

fmt.Println(bson.UnmarshalJSON(dialog.Dialog.Data, &a))

结果是:

json: unknown constant "l"

正如你所看到的,我不得不从Raw类型中提取Data,我不认为这是最好的方法,因为Raw类型中还有未使用的Kind字段。另外,这个l是什么意思?

更新2

我原以为必须将其解组为JSON类型才能使用,但我发现直接解组为map更好,所以这是代码:

var a bson.M
fmt.Println(bson.Unmarshal(dialog.Dialog.Data, &a))
fmt.Println(a)

这对我起作用了 使用bson.Raw从查询中返回完整的JSON。

然而,我仍然忽略了Raw类型的Kind字段。有没有更好的方法?

英文:

I'm trying to search for this document:

"meta": {
	"pageId": "...",
	"userId": "...",
	"ver": "0",
},
"dialog": {
 ...

 }

and get the entire "dialog" as a JSON, so I created this struct:

type Dialog struct {
    Dialog bson.Raw `json:"dialog" bson:"dialog"`
}

So I query the document like this:

dialog := Dialog{}
query := c.Find(locate).One(&dialog)

and when I print dialog, I get a bunch of numbers, which I believe are the raw bytes from the query.

The question is: how to unmarshal it into a JSON object?

The only thing I've found about this are https://stackoverflow.com/questions/25276884/marshal-into-a-bson-raw (which doesn't explain how to unmarshal into a json)

Update

Following https://stackoverflow.com/questions/39785289/how-to-marshal-json-string-to-bson-document-in-golang-for-writing-to-mongodb, I did:

fmt.Println(bson.UnmarshalJSON(dialog.Dialog.Data, &a))

which gets me:

json: unknown constant "l"

As you can see I had to extract the Data from the Raw type, I don't think this is the best way to do it since there's the Kind field which is not being used. Also, what's this 'l'?

Update 2

I thought I had to Unmarshal into a JSON type in order to work with it but I've found that's better to Unmarshal to a map directly, so here it is:

var a bson.M
fmt.Println(bson.Unmarshal(dialog.Dialog.Data, &a))
fmt.Println(a)

It worked for me 使用bson.Raw从查询中返回完整的JSON。

However, I'm still ignoring the Kind field of the Raw type. Is there a better way to do it?

答案1

得分: 2

JSON不是一种类型,因此无法将其解组为JSON类型的值。JSON是一种结构化数据的文本表示形式。

bson.Raw也不等于JSON表示形式,因此不可避免地需要进行某种转换。

你可以将其解组为interface{}类型的值,然后使用json.Marshal()来“渲染”JSON表示形式。

如果你希望这个过程是“自动”的,可以创建一个名为JSONStr的新类型,并通过它实现bson.Setterbson.Getter接口。

以下是示例代码:

type JSONStr string

func (j *JSONStr) SetBSON(raw bson.Raw) (err error) {
    var i interface{}
    if err = raw.Unmarshal(&i); err != nil {
        return
    }
    data, err := json.Marshal(i)
    if err != nil {
        return
    }
    *j = JSONStr(data)
    return
}

func (j *JSONStr) GetBSON() (interface{}, error) {
    var i interface{}
    if err := json.Unmarshal([]byte(*j), &i); err != nil {
        return nil, err
    }
    return i, nil
}

使用这个JSONStr类型:

type Dialog struct {
    Dialog JSONStr `bson:"dialog"`
}

更新:

如果你不需要真正的JSON文本表示形式,只需使用interface{}类型即可:

type Dialog struct {
    Dialog interface{} `bson:"dialog"`
}

然后可以像这样获取JSON文本:

var dialog Dialog
// 加载对话
data, err := json.Marshal(dialog.Dialog)
if err != nil {
    // 处理错误
}
fmt.Println(string(data))

(基本上,这就是JSONStr.SetBSON()方法的作用。)

请注意,interface{}将“覆盖”所有数据结构。如果你知道它是一个对象,可以使用map。如果你知道它是一个数组,可以使用切片,等等。你还可以使用任何具体类型。

英文:

JSON is not a type, so you can't unmarshal into a value of type JSON. JSON is a textual representation of some structured data.

bson.Raw is also not equal to JSON representation, so some kind of transformation is inevitable.

What you may do is unmarshal into a value of type interface{}, and then use json.Marshal() to "render" the JSON representation.

If you want this to be "automatic", you may create a new type called JSONStr, and you may implement the bson.Setter and bson.Getter interfaces by it.

This is how it could look like:

type JSONStr string

func (j *JSONStr) SetBSON(raw bson.Raw) (err error) {
	var i interface{}
	if err = raw.Unmarshal(&i); err != nil {
		return
	}
	data, err := json.Marshal(i)
	if err != nil {
		return
	}
	*j = JSONStr(data)
	return
}

func (j *JSONStr) GetBSON() (interface{}, error) {
	var i interface{}
	if err := json.Unmarshal([]byte(*j), &i); err != nil {
		return nil, err
	}
	return i, nil
}

And using this JSONStr type:

type Dialog struct {
	Dialog JSONStr `bson:"dialog"`
}

Update:

If you don't really want a JSON text representation, just use type interface{}:

type Dialog struct {
	Dialog interface{} `bson:"dialog"`
}

And obtain the JSON text like this:

var dialog Dialog
// load a dialog
data, err := json.Marshal(dialog.Dialog)
if err != nil {
	// handle error
}
fmt.Println(string(data))

(Basically this is what the JSONStr.SetBSON() method did exactly.)

Note that interface{} will "cover" all data structures. If you know it's an object, you may use a map. If you know it's an array, you may use a slice, etc. You may also use any concrete type.

huangapple
  • 本文由 发表于 2017年2月22日 15:42:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/42385436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定