douxieqiu0651 2019-05-17 10:57
浏览 222
已采纳

无法使用gopkg.in/yaml.v2解压缩具有缩进或空值的yaml文件

I have the following YML file called test.yml

user_name:Agent1
org_info:
  first:hello
  second:world

I tried to unmarshal test.yml with the following golang code

package main

import (
  "log"
  "io/ioutil"
  "gopkg.in/yaml.v2"
)

func main() {

  content, _ := ioutil.ReadFile("./test.yml")
  var t interface{}
  yaml.Unmarshal(content, &t)
  log.Println(t)
}

But the log.Println(t) gives nil. I reduced the test.yml file to this:

user_name:Agent1
org_info:

But the log.Println(t) still gives nil.

How do I use golang to unmarshal a yaml file that has an unpredictable schema with fields that have no values or fields that lead to nested and indented sub fields?

Or is there another golang yaml parser I should be using?

  • 写回答

1条回答 默认 最新

  • dongwuchu0314 2019-05-17 11:19
    关注

    yaml.Unmarshal() returns an error:

    yaml: line 2: mapping values are not allowed in this context

    Never skip error checks:

    var t interface{}
    err = yaml.Unmarshal(content, &t)
    if err != nil {
        log.Fatal(err)
    }
    

    Adding the missing spaces after the colon should, make them into YAML value indicators:

    user_name: Agent1
    org_info:
      first: hello
      second: world
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答