string - 当 YAML 文件包含 unicode 字符(如 "a\u0000b")时,在 golang 中读取 YAML 文件

标签 string go unicode yaml

我在读取 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/

相关文章:

ios - 为什么我们应该使用 NSString 的 uppercaseStringWithLocale 来获取正确的大写字符串?

javascript - Node js中的字符串正则表达式替换

相当于 python 字符串切片的 JavaScript

docker - 在 docker 文件中执行 go build -o/bin/go_docker 时找不到二进制文件

go - slice 可以访问另一个超出范围的 slice ,但索引超出范围会导致 panic

c - 如何初始化一个 wchar_t 变量?

windows - Emacs 在重新加载时不显示 Unicode

C++ 子字符串为什么要这样做?

java - ReplaceAll 和 "不替换

go - 在不同类型的结构之间复制公共(public)字段