首页 > 解决方案 > POST 请求的 JSON 正文

问题描述

我正在为 POST 请求构建一个主体

relativeurl := "this-is-a-test-url"

postBody := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": \"%s\"}]}", relativeurl)

当我做 afmt.PrintlnpostBody,我看到:

{
"requests": [
    {
        "httpMethod": "GET",
        "relativeUrl": "this-is-a-test-url"}]}

但网址需要一个 JSON:

{
    "requests": [
        {
            "httpMethod": "GET",
            "relativeUrl": "this-is-a-test-url"
        }
]
}

我构建帖子正文的方式是否错误?

标签: jsongogo-http

解决方案


只是提到另一种正确转义 JSON 字符串的方法:

// call the json serializer just on the string value :
escaped, _ := json.Marshal(relativeUrl)
// the 'escaped' value already contains its enclosing '"', no need to repeat them here :
body := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": %s}]}", escaped)

https://play.golang.org/p/WaT-RCnDQuK


推荐阅读