type Demo struct {
Content string `json:"content"`
}
func main() {
var demo Demo
str := "{\"content\":\"你好\r\n小满\"}"
err := json.Unmarshal([]byte(str), &demo)
if err != nil {
log.Fatal(err)
return
}
}
跑上面的代码,会报题头的错误。后来查了下相关资料,发现是这么说的 The first is that newline is not allowed in a JSON string. Use the two bytes \n to specify a newline, not an actual newline. If you use an interpreted string literal, then the \ must be quoted with a \.
也就是 json 在解析 \r\n 时需要在 \ 前面再加上转义符
str := "{\"content\":\"你好\\r\\n小满\"}"
另外,在 golang 中,用反引号也可以解决
str := `{"content":"你好\r\n小满"}`