将任意字符串编码为 JSON 格式的 HTTP 响应。

huangapple go评论73阅读模式
英文:

Encode arbitrary string to JSON in http response

问题

我有一个 JSON 字符串,我想将其编码为 JSON 并作为 HTTP 响应返回。

以下代码会返回一个字符串:

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

我试图首先将字符串编组为 JSON。这将给我另一个随机字节的字符串。

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

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)

答案1

得分: 2

解决方案(w 是 responseWriter)

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

Solution (w is the responseWriter)

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

huangapple
  • 本文由 发表于 2015年5月28日 01:25:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/30489268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定