MrDuk
MrDuk

Reputation: 18282

How can I join an array into a string while preserving quotes?

I have a string: {"isRegion":true, "tags":?}

Where I want to join an array of strings in place of ?, surrounded by quotes.

My current attempt doesn't quite work:

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

The above gives the output: "tags":["prod\",\"stats"]

I instead need the quotes to persist without escaping: "tags":["prod","stats"]

Upvotes: 2

Views: 6675

Answers (1)

Ivan Beldad
Ivan Beldad

Reputation: 2371

Your tricky approach fixed:

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

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

The easy and correct way:

// 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))

You can either use json.MarshalIndent or json.Marshal to encode JSON, and json.UnMarshal to decode. Check more info about this at the official documentation.

Upvotes: 7

Related Questions