How to Write bson Array to ResponseWriter

时间:2019-01-18 19:06:57

标签: mongodb go deserialization bson

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 个答案:

答案 0 :(得分:1)

改为使用bons.M

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)
相关问题