我对 Golang 完全陌生。
我不知道如何防止它在 {...}
中包装 JSON。
举个例子:
package main
import (
"net/http"
"bytes"
"fmt"
)
func main() {
request, _ := http.NewRequest("POST", "http://example.com", bytes.NewBufferString(`["foobar":42]`))
fmt.Println(request)
}
这个例子会输出:
&{POST http://example.com HTTP/1.1 1 1 map[] {["foobar":42]} 13 [] false example.com map[] map[] <nil> map[] <nil> <nil>}
如您所见,我们的数组(顺便说一下,它是有效的 JSON)现在被包装到 {
和 }
中。我想不出如何解决这个问题。
谢谢!
最佳答案
这是一个 pretty-print ,参见 func Println(a ...interface{}) (n int, err error)
文档:
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.
您可以使用 strings.Trim(st, "{}")
从字符串中删除 {}
。
您可以对 JSON 使用 Marshal
和 Unmarshal
,就像这个工作示例代码:
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
}
输出:
{42}
{"foobar":42}
"foobar":42
关于json - Golang 用方括号包裹一个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956290/