druzuz321103 2019-06-08 11:46 采纳率: 100%
浏览 233
已采纳

进行YAML解析:必填字段

Summary: I need to parse data in YAML format into golang struct. It there a way (library, attributes) to make some of the fields mandatory, i.e. to make Unmarshal function return the error in case if some field doesn't exist?

Example what is wanted: Unmarshal function in this code should raise an error because input data doesn't contain 'b' field.

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

type TestStruct struct {
    FieldA string `yaml:"a"`
    FieldB string `yaml:"b"`
}

func main() {
    input := []byte(`{a: 1}`)
    var output TestStruct

    _ = yaml.Unmarshal(input, &output)
}
  • 写回答

1条回答 默认 最新

  • dongyu1979 2019-06-08 15:09
    关注

    You can use this library's HasZero method to check wether there are any missing values in a struct. This will return true or false depending wether the struct is completely filled or not. Please see the playground example to get an idea.

    But if you specifically need to tell what field is missing, you need to check wether the value is nil like in the example below.

    package main
    import (
       "fmt"
       "errors"
      "gopkg.in/yaml.v2"
    )
    
    type TestStruct struct {
      FieldA  string `yaml:"a"`
      FieldB  string `yaml:"b"`
    }
    
    func main() {
      input := []byte(`{a: 1}`)
    
      var output TestStruct 
      if err := output.ParseFromFile(input); err != nil {
         fmt.Println(err)
      }
      fmt.Println(output)     
    }
    
    func (output *TestStruct) ParseFromFile(data []byte) error {
    
      if err := yaml.Unmarshal(data, output); err != nil {
        return err
      }
    
      if output.FieldA == "" {
        return errors.New("Blank Field A")
      }
      if output.FieldB == "" {
        return errors.New("Blank Field B")
      }
    
      return nil
    }
    

    Playground example if you need to specifically return an error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)