jsongonegroni

Encode arbitrary string to JSON in http response


I have a string of JSON that I want to encode as json into an http response.

This returns a string in the response:

str := "{\"key1\":{\"key2\":\"value1\",\"key3\":\"value2\"}}"
err := json.NewEncoder(w).Encode(str)

I'm trying to first marshal the string to JSON. Which gives me another string of random bytes.

str := "{\"key1\":{\"key2\":\"value1\",\"key3\":\"value2\"}}"
js, _ := json.Marshal(str)
err := json.NewEncoder(w).Encode(js)

Solution

  • Solution (w is the responseWriter)

    str := "{\"key1\":{\"key2\":\"value1\",\"key3\":\"value2\"}}"
    w.Write([]byte(str))