MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Come convertire (marshal) una stringa JSON in un documento BSON per MongoDB

Il pacchetto gopkg.in/mgo.v2/bson contiene una funzione chiamata UnmarshalJSON che fa esattamente ciò che ti serve.

Il parametro data deve contenere la tua stringa JSON come valore []byte.

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

Esempio:

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