json - Golang 用方括号包裹一个 JSON

标签 json go

我对 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 使用 MarshalUnmarshal,就像这个工作示例代码:

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/

相关文章:

javascript - 动态设置jquery数据表列的数据源

windows - 如何使用Go创建的exe创建Windows服务?

go - 如何在Golang中正确使用指针

java - Spring Boot - 使用自定义对象数组 JSON 序列化自定义对象

javascript - 在 React Native 中使用 axios 从带有参数的 GET 方法的 HTTP 响应

java - 如何读取 json 文件,并使用 GSON 将其转换为 POJO

regex - 如何在golang中使用正则表达式替换字符串中的表情符号字符

json - 如何从 MacOS 上的 Excel 中的 HTTP 端点检索 JSON 并解析它?

amazon-web-services - golang附加到二维 slice

postgresql - 如何使用GORM在Postgres的JSONB字段中插入数据