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

后端 未结 3 451
野的像风
野的像风 2021-02-07 16:23

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 Go structs for marshal

相关标签:
3条回答
  • 2021-02-07 16:57

    mongo-go-driver has a function bson.UnmarshalExtJSON that does the job.

    Here's the example:

    var doc interface{}
    err := bson.UnmarshalExtJSON([]byte(`{"foo":"bar"}`), true, &doc)
    if err != nil {
        // handle error
    }
    
    0 讨论(0)
  • 2021-02-07 17:01

    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)
    }
    
    0 讨论(0)
  • 2021-02-07 17:12

    There is no longer a way to do this directly with supported libraries (e.g. the mongo-go-driver). You would need to write your own converter based on the bson spec.

    0 讨论(0)
提交回复
热议问题