如何在golang yaml解析器中保留空格和换行符?

时间:2015-02-09 06:15:16

标签: parsing go yaml

我想要像

这样的东西
Some text here,  
    indented text here
    next indented texr here

我试过这个yaml风格

key: |
    Some text here,
        indented text here
        next indented text here

上面的yaml代码仅保留换行符,但会丢弃缩进的空格。 如何保留这些额外的空间?

我用来解析yaml文件的代码 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
}

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 }

1 个答案:

答案 0 :(得分:0)

我不确定您使用哪个解析器来解析YAML,但这里有一个非常好用的代码片段,我使用了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"))
}