如何解码转义字符串

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

How to unmarshal escaped string

问题

我有一个关于在Go中解析JSON字符串的愚蠢问题。

以下是代码:

package main

import (
	"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

看起来解析器真的不喜欢 \\\" 这个序列。我该如何解决这个问题?

英文:

I have a dumb question regarding JSON string unmarshalling in Go

Here's the code:

package main

import (
	"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)
}

The output:

{"just_a_key":"Some text "some quoted text""}
invalid character 's' after object key:value pair

Seems like unmarshaller really hates '\"' sequence. How can I fix the issue?

答案1

得分: 3

您的输入不是有效的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"]

如果您使用原始字符串字面量(不需要Go转义,只需要JSON转义),那么这将更加简单和清晰:

s := `{"just_a_key":"Some text \"some quoted text\""}`

这将输出相同的结果。在Go Playground上尝试一下这个方法。

英文:

Your input is not valid JSON. To have a double quote inside a JSON string, you have to escape it. Use the \" sequence for a double quote character.

But since you're using an interpreted Go string literal to specify the JSON text, the \" sequence also have to be escaped according to the Go interpreted rules, where a backslash is \\ and the double quote is \", so the JSON \" sequence must appear as \\\" in a Go interpreted string literal:

s := "{\"just_a_key\":\"Some text \\\"some quoted text\\\"\"}"

With this change output is (try it on the Go Playground):

{"just_a_key":"Some text \"some quoted text\""}
map[just_a_key:Some text "some quoted text"]

It's much easier and cleaner if you use raw string literal (where no Go escaping is needed, just the JSON escaping):

s := `{"just_a_key":"Some text \"some quoted text\""}`

This will output the same. Try this one on the Go Playground.

huangapple
  • 本文由 发表于 2022年2月11日 18:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/71078940.html
匿名

发表评论

匿名网友

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

确定