3 回答

TA貢獻1951條經驗 獲得超3個贊
只是提到另一種正確轉義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

TA貢獻1827條經驗 獲得超9個贊
您的兩個 JSON 輸出示例既有效又在功能上等效??崭裨?JSON 中并不重要。請參閱 JSON.org 中的以下內容:
可以在任何一對令牌之間插入空格。
您可以使用或在線 JSON 解析器輕松測試和格式化 JSON。encoding/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
添加回答
舉報