POST请求的JSON主体

huangapple go评论87阅读模式
英文:

JSON body for POST request

问题

我正在构建一个用于POST请求的请求体。

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

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

当我使用fmt.Println打印postBody时,我看到:

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

但是URL需要一个JSON格式的请求体:

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

我构建请求体的方式有问题吗?

英文:

I am building a body for a POST request

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

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

When I do a fmt.Println of postBody, I see:

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

but the url is expecting a JSON:

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

Is the way I build the post body wrong?

答案1

得分: 2

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

// 仅对字符串值调用 json 序列化器:
escaped, _ := json.Marshal(relativeUrl)
// 'escaped' 值已经包含了它的封闭 '""',这里不需要重复:
body := fmt.Sprintf("{\"requests\": [{\"httpMethod\": \"GET\",\"relativeUrl\": %s}]}", escaped)

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

英文:

Just to mention another way to correctly escape a JSON string :

// 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

答案2

得分: 1

你的两个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

英文:

Your two JSON output examples are both valid and functionally equivalent. White space is not significant in JSON. See the following at JSON.org:

> Whitespace can be inserted between any pair of tokens.

You can test and format your JSON easily using encoding/json or an online JSON parser.

However, the approach you are using is prone to error since your URL needs to be properly escaped. For example, if your URL has a double quote, ", in it, your code will produce invalid JSON.

In Go, it's much better to create some structs to encode. For example:

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))
}

Here's a running example:

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

答案3

得分: 0

你可以使用 json 包来处理 JSON 输入和输出。使用 json.Unmarshal 函数将 JSON 转换为 Golang 结构,使用 json.Marshal 函数将 Golang 结构转换为 JSON。

英文:

You can use json package to handle json inputs and outputs. Use json.Unmarshal function to convert json to golang structure and use json.Marshal function to convert golang structure to json.

huangapple
  • 本文由 发表于 2021年7月19日 14:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/68436289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定