如何在Golang的YAML解析器中保留空格和换行符?

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

how to preserve spaces and newline in golang yaml parser?

问题

我想要类似这样的内容:

<pre>这里是一些文本,
这里是缩进的文本
下一个缩进的文本</pre>

我尝试了这种 YAML 格式:
<pre>
key: |
这里是一些文本,
这里是缩进的文本
下一个缩进的文本
</pre>

上述的 YAML 代码只保留了换行符,但丢弃了缩进的空格。如何保留这些额外的空格?

我用来解析 YAML 文件的代码:
<code>
package main

import (
    "os"
    "fmt"
    "github.com/kylelemons/go-gypsy/yaml"
)

func main(){
    map_,err:=Parse()
fmt.Println(map_.Key("Key"),err)
}

func Parse() (yaml.Map, error) {
    file, err := os.Open("testindent.yaml")
        if err != nil {
        return nil, err
    }
    node, err := yaml.Parse(file)
        if err != nil {
            return nil, err
    }
    nodes := node.(yaml.Map)
    return nodes, nil
}

</code>

英文:

I want something like

<pre>Some text here,
indented text here
next indented texr here</pre>

I tried this yaml style
<pre>
key: |
Some text here,
indented text here
next indented text here
</pre>

the above yaml code preserves only the newline but discards the indented spaces.
How to preserve those extra spaces?

code I used to parse the yaml file
<code>
package main

import (
    &quot;os&quot;
    &quot;fmt&quot;
    &quot;github.com/kylelemons/go-gypsy/yaml&quot;
)

func main(){
    map_,err:=Parse()
fmt.Println(map_.Key(&quot;Key&quot;),err)
}

func Parse() (yaml.Map, error) {
	file, err := os.Open(&quot;testindent.yaml&quot;)
    	if err != nil {
    	return nil, err
	}
    node, err := yaml.Parse(file)
        if err != nil {
	        return nil, err
    }
    nodes := node.(yaml.Map)
    return nodes, nil
}

</code>

答案1

得分: 2

我不确定你使用的是哪个解析器来解析YAML,但是这里有一段代码片段,它使用了viper库。

testviber.yaml

invoice: 34843
date   : 2001-01-23
abc: |
   曾经有一个来自伊灵的矮个子
   他上了一辆去大吉岭的公共汽车
       车门上写着
       “请不要在地板上吐痰”
   所以他小心翼翼地吐在了天花板上
last_invoice: 34843

testviber.go

package main

import (
	"fmt"

	"github.com/spf13/viper"
)

func main() {
	viper.SetConfigName("testviber")
	viper.ReadInConfig()
	fmt.Printf("%v", viper.Get("abc"))
}
英文:

I am not sure which parser are you using to parse the YAML, but here is a snippet which works pretty good, I used viper.

testviber.yaml

invoice: 34843
date   : 2001-01-23
abc: |
   There once was a short man from Ealing
   Who got on a bus to Darjeeling
       It said on the door
       &quot;Please don&#39;t spit on the floor&quot;
   So he carefully spat on the ceiling
last_invoice: 34843

testviber.go

package main

import (
	&quot;fmt&quot;

	&quot;github.com/spf13/viper&quot;
)

func main() {
	viper.SetConfigName(&quot;testviber&quot;)
	viper.ReadInConfig()
	fmt.Printf(&quot;%v&quot;, viper.Get(&quot;abc&quot;))
}

huangapple
  • 本文由 发表于 2015年2月9日 14:15:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/28403829.html
匿名

发表评论

匿名网友

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

确定