go - 如何在保留引号的同时将数组连接到字符串中?

标签 go

我有一个字符串:{"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/

相关文章:

go - 包级集合

Go 1.0.2 zlib 压缩时如何提高速度

unicode - 无效的 Unicode 代码点 0xd83f

orm - 无法使用Beego的ORM .All()

git - 如何将 go.mod 中的 Go 模块依赖项指向 repo 中的最新提交?

testing - 在 go test 中处理命令行参数

datetime - 一次 time.Parse 错误,我做错了什么?

web-applications - Go Webapp & Nginx : Confusion about listening, fastcgi & 反向代理

go - slice 的有效分配(上限与长度)

google-app-engine - 如何在 Google App Engine Standard Env for Go 中获取 request.RemoteAddr 和 X-AppEngine-Country、Region 等的输出?