英文:
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 (
"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>
答案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
"Please don't spit on the floor"
So he carefully spat on the ceiling
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"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论