Reputation: 2909
I'm totally new to Golang.
I can not figure out how to prevent it to wrap JSON in the {...}
.
So example:
package main
import (
"net/http"
"bytes"
"fmt"
)
func main() {
request, _ := http.NewRequest("POST", "http://example.com", bytes.NewBufferString(`["foobar":42]`))
fmt.Println(request)
}
This example will output:
&{POST http://example.com HTTP/1.1 1 1 map[] {["foobar":42]} 13 [] false example.com map[] map[] <nil> map[] <nil> <nil>}
As you can see our array (which is BTW valid JSON) is now wrapped into {
and }
. I ran out of ideas how to fix that.
Thanks!
Upvotes: 0
Views: 4907
Reputation:
It's a pretty printing, see func Println(a ...interface{}) (n int, err error)
Docs:
Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered.
You may use strings.Trim(st, "{}")
to remove {}
from string.
You may use Marshal
and Unmarshal
for JSON, like this working sample code:
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type Foo struct {
Foobar int `json:"foobar"`
}
func main() {
str := `{
"Foobar": 42
}`
var d Foo
err := json.Unmarshal([]byte(str), &d)
if err != nil {
log.Fatal(err)
}
fmt.Println(d) // {42}
fmt.Println()
body, err := json.Marshal(d)
if err != nil {
panic(err)
}
st := string(body)
fmt.Println(st) //{"foobar":42}
fmt.Println(strings.Trim(st, "{}")) // "foobar":42
}
output:
{42}
{"foobar":42}
"foobar":42
Upvotes: 4