duanping2005 2019-01-18 19:06
浏览 70
已采纳

如何将bson数组写入ResponseWriter

I am writing code in GoLang. As part of it, I generated bson array by querying a collection in MongoDB using github.com/mongodb/mongo-go-driver/mongo, github.com/mongodb/mongo-go-driver/bson. I need to write this response to http.ResponseWriter. When I attempt to do this using json.Marshal(BsonArrayReceived), response that is written to ResponseWriter has different document structure than JSON document structure stored in MongoDB. So, wanted to know the right way to write query results to ResponseWriter.

Let's say there are two documents that meet my query criteria - cat, dog

cat := bson.D{{"Animal", "Cat"}}
dog := bson.D{{"Animal", "Dog"}}

So resultant bson Array I am creating would be something like below

response := bson.A
response = append(response, cat)
response = append(response, dog)

My current code that did not work is below

writer.Header().Set("Content-Type", "application/json")    
json.err := json.Marshal(response)
writer.Write(json)

Expected output would be

[{"Animal":"Cat"},{"Animal":"Dog"}]

Actual output I receive is

[{{"Key":"Animal"},{"Value":"Cat"}},{{"Key":"Animal"},{"Value":"Dog"}}]

So my question is how do I write to ResponseWriter so I preserve the JSON document array structure. I prefer not to use custom Marshal/UnMarshal as that would mean solution is specific and need changes if I change JSON structure

  • 写回答

1条回答 默认 最新

  • dqdt45183 2019-01-21 00:32
    关注

    Use bons.M instead.

    cat := bson.M{"Animal": "Cat"}
    dog := bson.M{"Animal": "Dog"}
    response := bson.A{}
    response = append(response, cat)
    response = append(response, dog)
    writer.Header().Set("Content-Type", "application/json")
    json, _ := json.Marshal(response)
    writer.Write(json)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题