douyi3676 2017-02-22 07:42
浏览 471
已采纳

MongoDB使用bson.Raw从查询返回整个JSON

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 Marshal into a bson.Raw (which doesn't explain how to unmarshal into a json)

Update

Following 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 :)

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

  • 写回答

1条回答 默认 最新

  • douxing2156 2017-02-22 08:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误