如何在保留引号的同时将数组加入字符串?

MrD*_*Duk 1 go

我有一个字符串: {"isRegion":true, "tags":?}

我想加入一个字符串数组代替?, 用引号括起来。

我目前的尝试不太奏效:

jsonStr := []byte(fmt.Sprintf(`{"isRegion":true, "tags":[%q]}, strings.Join(tags, `","`)))
Run Code Online (Sandbox Code Playgroud)

以上给出了输出: "tags":["prod\",\"stats"]

相反,我需要引号保持不变而不会转义: "tags":["prod","stats"]

Iva*_*dad 6

您的棘手方法已修复:

tags := []string{"prod", "stats"}

jsonStr := []byte(fmt.Sprintf(`{"isRegion":true, "tags":["%s"]}`, 
    strings.Join(data, `", "`)))
Run Code Online (Sandbox Code Playgroud)

简单而正确的方法:

// 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))
Run Code Online (Sandbox Code Playgroud)

您可以使用 json.MarshalIndent 或 json.Marshal 对 JSON 进行编码,使用 json.UnMarshal 进行解码。在官方文档中查看有关此内容的更多信息。