Search code examples
jsonmongodbgomarshallingbson

How to render a json string from bson document


I am struggling to create a valid JSON string from a BSON document in Go for an API. Let's say I have an object like this:

type MyObject struct {
    Name string
}

I call my database which returns to me a cursor containing many documents as: [{"Name": "object_name"}, ...]

I am able to retrieve all the documents via a loop like

for cur.Next(ctx) {
    var obj MyObject
    err := cur.Decode(&obj)
    //then display error if there's one        
}

And now I would like to end up with a JSON string containing all the documents my database returned in order to send it via HTTP.

Because, if use I fmt.Println(obj)I end up with something like this: [{object1_name} {object2_name} ...] which is, according to me, not a valid format that I can use for an API.

I know json.Marshal(obj) can actually encode to valid JSON and I can decode it with os.Stdout.Write(obj) but I didn't manage to store this valid string in a variable. How can I manage to do this?


Solution

  • From Golang documentation for json package

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        type ColorGroup struct {
            ID     int      `json:"id"`
            Name   string   `json:"name"`
            Colors []string `json:"colors"`
        }
        group := ColorGroup{
            ID:     1,
            Name:   "Reds",
            Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
        }
        b, err := json.Marshal(group)
        if err != nil {
            fmt.Println("error:", err)
        } else {
            str := string(b)
            fmt.Println("stringified json is:", str)
    
        }
    }
    
    
    
    Output
    stringified json is: {"id":1,"name":"Reds","colors":["Crimson","Red","Ruby","Maroon"]}
    

    The json.Marshal return two values - a byte array and error If error is nil then you can obtain the string by converting byte array to string using str := string(b)