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

时间:2018-04-18 18:35:51

标签: go

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

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

我目前的尝试并不是很有效:

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

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

我需要在没有转义的情况下保持引号:"tags":["prod","stats"]

1 个答案:

答案 0 :(得分:1)

你的方法很复杂:

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上查看有关此内容的详情。