0

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?

0

1 Answer 1

1

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)

1
  • You saved me hours of struggling. I'm new to Go and didn't know we could convert a byte array to a string. Thanks a lot! Nov 13, 2019 at 14:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.