登录
首页 >  Golang >  Go问答

POST 请求的 JSON 正文

来源:stackoverflow

时间:2024-03-29 15:54:31 115浏览 收藏

一分耕耘,一分收获!既然都打开这篇《POST 请求的 JSON 正文》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在为 post 请求构建主体

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

postbody := fmt.sprintf("{\"requests\": [{\"httpmethod\": \"get\",\"relativeurl\": \"%s\"}]}", relativeurl)

当我执行 postbodyfmt.println 时,我看到:

{
"requests": [
    {
        "httpmethod": "get",
        "relativeurl": "this-is-a-test-url"}]}

但 url 需要 json:

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

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


正确答案


仅提一下正确转义 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

您的两个 json 输出示例均有效且功能等效。空格在 json 中并不重要。请参阅以下内容:JSON.org

您可以使用 encoding/json 或在线 json 解析器轻松测试和格式化 json。

但是,您使用的方法很容易出错,因为您的 url 需要正确转义。例如,如果您的 url 中包含双引号 ",您的代码将生成无效的 json。

在 go 中,最好创建一些结构体进行编码。例如:

package main

import (
    "encoding/json"
    "fmt"
)

type RequestBody struct {
    Requests []Request `json:"requests"`
}

type Request struct {
    HTTPMethod  string `json:"httpMethod"`
    RelativeURL string `json:"relativeUrl"`
}

func main() {
    body := RequestBody{
        Requests: []Request{{
            HTTPMethod:  "GET",
            RelativeURL: "this-is-a-test-url",
        }},
    }

    bytes, err := json.MarshalIndent(body, "", "  ")
    if err != nil {
        panic(err)
    }

    fmt.Println(string(bytes))
}

这是一个运行示例:

https://play.golang.org/p/c2iU6blG3Rg

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>