gpt4 book ai didi

mongodb - 我如何将 BSON 文档转换为 map[string]interface{}

转载 作者:IT王子 更新时间:2023-10-29 02:01:03 24 4
gpt4 key购买 nike

我试图将游标的数据解码成一个map[string]interface{},我直接试了但是它根本不起作用,所以我发现我必须将它转换为BSON文档并且接下来将其转换为 map[string]interface{},最后转换为 JSON 字符串。我尝试了以下代码:

...
for cursor.Next(context.Background()) {
err = cursor.Decode(&itemBson)
...
b, err := bson.Marshal(itemBson)
...
err = bson.Unmarshal(b, &itemMap)
...
}
...

但是bson文档有如下值:

map[_id:ObjectID("5c2d0809a49bad7d547ec028") applications:bson.Array[bson.Document{bson.Element{"enabled": true}}] userName:coto userUUID:df2dea92-c189-53b3-aafe-485d0be23bee]

并将 map 解析为 JSON:

{"_id":"5c2d0809a49bad7d547ec028","applications":[{}],"userName":"coto","userUUID":"df2dea92-c189-53b3-aafe-485d0be23bee"

如您所见,键“applications”在 JSON 中是空的,但它在 BSON 文档中确实有内容。我不知道为什么数据会消失。

我该如何解决这个错误?谢谢。

最佳答案

已解决:

我使用以下代码解决了这个错误:

var jsonDocuments []map[string]interface{}
var byteDocuments []byte

var bsonDocument bson.D
var jsonDocument map[string]interface{}
var temporaryBytes []byte

for cursor.Next(context.Background()) {
err = cursor.Decode(&bsonDocument)

...

temporaryBytes, err = bson.MarshalExtJSON(bsonDocument, true, true)

...

err = json.Unmarshal(temporaryBytes, &jsonDocument)

...

jsonDocuments = append(jsonDocuments, jsonDocument)
}

关于mongodb - 我如何将 BSON 文档转换为 map[string]interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54133724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com