我有一个关于 Go 中 JSON 字符串解组的愚蠢问题这是代码:package mainimport ( "bytes" "encoding/json" "fmt")func main() { s := "{\"just_a_key\":\"Some text \"some quoted text\"\"}" fmt.Println(s) buf := bytes.NewBufferString(s) data := make(map[string]string) err := json.Unmarshal(buf.Bytes(), &data) if err != nil { fmt.Println(err) } fmt.Println(data)}输出:{"just_a_key":"Some text "some quoted text""}invalid character 's' after object key:value pair似乎 unmarshaller 真的很讨厌 '\"' 序列。我该如何解决这个问题?
1 回答

沧海一幻觉
TA贡献1824条经验 获得超5个赞
您的输入不是有效的 JSON。要在 JSON 字符串中包含双引号,您必须对其进行转义。使用\"双引号字符的序列。
但是由于您使用解释的Go 字符串文字来指定 JSON 文本,因此\"还必须根据 Go 解释规则对序列进行转义,其中反斜杠是\\,双引号是\",因此 JSON\"序列必须显示\\\"为Go 解释字符串文字:
s := "{\"just_a_key\":\"Some text \\\"some quoted text\\\"\"}"
有了这个更改输出(在Go Playground上尝试):
{"just_a_key":"Some text \"some quoted text\""}
map[just_a_key:Some text "some quoted text"]
如果您使用原始字符串文字(不需要转义,只需要 JSON 转义),它会更容易和更清晰:
s := `{"just_a_key":"Some text \"some quoted text\""}`
这将输出相同的内容。在Go Playground上试试这个。
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报
0/150
提交
取消