我有一个字符串:{"isRegion":true, "tags":?}
我想加入一个字符串数组来代替 ?
,用引号括起来。
我目前的尝试不太奏效:
jsonStr := []byte(fmt.Sprintf(`{"isRegion":true, "tags":[%q]}, strings.Join(tags, `","`)))
上面给出了输出:"tags":["prod\",\"stats"]
相反,我需要引号保留而不转义:"tags":["prod","stats"]
最佳答案
你的棘手方法已修复:
tags := []string{"prod", "stats"}
jsonStr := []byte(fmt.Sprintf(`{"isRegion":true, "tags":["%s"]}`,
strings.Join(data, `", "`)))
简单又正确的方法:
// This will be your JSON object
type Whatever struct {
// Field appears in JSON as key "isRegion"
IsRegion bool `json:"isRegion"`
Tags []string `json:"tags"`
}
tags := []string{"prod", "stats"}
w := Whatever{IsRegion: true, Tags: tags}
// here is where we encode the object
jsonStr, err := json.MarshalIndent(w, "", " ")
if err != nil {
// Handle the error
}
fmt.Print(string(jsonStr))
您可以使用 json.MarshalIndent 或 json.Marshal 对 JSON 进行编码,并使用 json.UnMarshal 进行解码。在 official documentation 查看更多相关信息.
关于go - 如何在保留引号的同时将数组连接到字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49906753/