3 回答

TA貢獻1836條經(jīng)驗 獲得超4個贊
將 JSON解組到 []interface{}并將結(jié)果插入到數(shù)據(jù)庫中。假設它c是一個mgo.Collection并且data是一個包含 JSON 值的 []byte,請使用以下代碼:
var v []interface{}
if err := json.Unmarshal(data, &v); err != nil {
// handle error
}
if err := c.Insert(v...); err != nil {
// handle error
}

TA貢獻1875條經(jīng)驗 獲得超3個贊
在這個例子中,我將存儲混合數(shù)組
測試字符串:= '[[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]'
在 mongodb 中作為 json:
{datum: [[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]}
package main
import (
"strings"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type datum2 struct {
Datum interface{} `json:datum`
}
var userCollection = db().Database("goTest").Collection("users") // get collection "users" from db() which returns *mongo.Client
func typeinterface2mongo() {
var datum2 datum2_instance
var interfacevalue []interface{}
test_string := `[[1,"a","b",2,"000000",[[1,2,3],[1,2,3]],"\"x","[y","'z",[[1,2,3],[1,2,3]]]]`
if err := json.Unmarshal([]byte(test_string), &interfacevalue); err != nil {
fmt.Println(err)
return
}
fmt.Println(test_string)
fmt.Println(interfacevalue)
datum2_instance.Datum=interfacevalue
userCollection.InsertOne(context.TODO(), datum2_instance)
fmt.Println(datum2_instance)
fmt.Println(datum2_instance.Datum)
}

TA貢獻1841條經(jīng)驗 獲得超3個贊
如果您已經(jīng)有 json 數(shù)據(jù),請從第 2 步開始操作。
如果您先有 Xml 數(shù)據(jù),則需要使用此包(“github.com/basgys/goxml2json”)轉(zhuǎn)換為 json 格式
type JsonFileResponse struct {
JsonData string `bson:"JsonData " json:"JsonData"`
}
step 1: jsonData, err := xml2json.Convert(xml)
if err != nil {
panic("getting error while converting xml to json",err)
}
step 2: session need to open by using your mongodb credentials.
collection := session.DB("database name").C("Collection Name")
err = collection.Insert(JsonFileResponse{JsonData :json.String()})
if err != nil {
log.Fatal(err)
}
- 3 回答
- 0 關(guān)注
- 739 瀏覽
添加回答
舉報