我在读取 YAML 文件时遇到问题,并且 YAML 文件包含 Unicode 字符转义。但是当我加载 YAML 文件并打印 fileInfo
时,包含 Unicode 字符转义的字符串(例如 'a\u0000b'
)在使用 unMarshal 时被转义()
函数。
这是我的 YAML 文件 (conf.yml
):
topicList:
- source: 'test'
target: 'temp'
- source: 'a\u0000b'
target: 'temp'
我的代码是:
import (
"fmt"
"io/ioutil"
"strings"
"gopkg.in/yaml.v2"
)
type Config struct {
TopicList []Topic `yaml:"topicList"`
}
type Topic struct {
Source string `yaml:"source" json:"source"`
Target string `yaml:"target" json:"target"`
}
func main() {
cfg, err := NewConfig("conf.yml")
if err != nil {
fmt.Println("load config fail: ", err)
}
for _, s := range cfg.TopicList {
fmt.Println("\n +++++ sourceTopic = ", s.Source)
if strings.Contains(s.Source, "\u0000") {
fmt.Println("\n topic contains unicode character. topic = ", s.Source)
}
}
}
func NewConfig(file string) (conf *Config, err error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return
}
conf = &Config{}
err = yaml.Unmarshal(data, conf)
return
}
结果是:
+++++ sourceTopic = test
+++++ sourceTopic = a\u0000b
但我期望的结果是:
+++++ sourceTopic = test
+++++ sourceTopic = ab
topic contains unicode character. topic = ab
为什么我得不到预期的答案?如何修复代码?谢谢!
最佳答案
代码很好(无需修复),问题是您在输入 YAML 中使用了单引号。单引号中的转义序列按原样解释(即:不解释),因此 'a\u0000b'
将表示确切的字符串 "a\u0000b "
,或者在 Go 中解释的字符串文字语法:"a\\u0000b"
。
相反,源 YAML 必须使用双引号:"a\u000b"
以解释/解码转义符。
引自YAML spec: Escape Sequences:
Note that escape sequences are only interpreted in double-quoted scalars. In all other scalar styles, the “\” character has no special meaning and non-printable characters are not available.
如果您将输入 YAML 更改为此:
topicList:
- source: 'test'
target: 'temp'
- source: "a\u0000b"
target: 'temp'
那么您的应用程序的输出将是:
+++++ sourceTopic = test
+++++ sourceTopic = ab
topic contains unicode character. topic = ab
关于string - 当 YAML 文件包含 unicode 字符(如 "a\u0000b")时,在 golang 中读取 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045115/