在Go中将CSV记录解组为struct [英] Unmarshal CSV record into struct in Go

查看:173
本文介绍了在Go中将CSV记录解组为struct的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题如何自动反序列化/ unmarshal记录从CSV文件到Go结构。



例如,我有

  type Test struct {
名称字符串
姓氏字符串
年龄int
}
  John;> 



Smith; 42
Piter; Abel; 50

有一种简单的方法来解散这些记录到struct,除非使用encoding / csv包读取记录,然后做类似

  record,_:= reader。 Read()
test:= Test {record [0],record [1],atoi(record [2])}

$ b似乎我已经做了CSV记录自动编组到结构(限于字符串和整数)。希望这将是有用的。



这是一个链接到操场: http://play.golang.org/p/kwc32A5mJf

  func Unmarshal(reader * csv .Reader,v interface {})错误{
record,err:= reader.Read()
如果err!= nil {
return err
}
s: = reflect.ValueOf(v).Elem()
如果s.NumField()!= len(record){
return& FieldMismatch {s.NumField(),len(record)}
}
for i:= 0; i< NumField(); i ++ {
f:= s.Field(i)
switch f.Type()。String(){
casestring:
f.SetString )
caseint:
ival,err:= strconv.ParseInt(record [i],10,0)
如果err!= nil {
return err
}
f.SetInt(ival)
默认值:
return& UnsupportedType {f.Type()。String()}
}
}
return nil
}

我会尝试创建github包是有人需要这个实施。


The problem how to automatically deserialize/unmarshal record from CSV file into Go struct.

For example, I have

type Test struct {
  Name string
  Surname string
  Age int
}

And CSV file contains records

John;Smith;42
Piter;Abel;50

Is there an easy way to unmarshal those records into struct except by using "encoding/csv" package for reading record and then doing something like

record, _ := reader.Read()
test := Test{record[0],record[1],atoi(record[2])}

解决方案

Seems I've done with automatic marshaling of CSV records into structs (limited to string and int). Hope this would be useful.

Here is a link to playground: http://play.golang.org/p/kwc32A5mJf

func Unmarshal(reader *csv.Reader, v interface{}) error {
    record, err := reader.Read()
    if err != nil {
        return err
    }
    s := reflect.ValueOf(v).Elem()
    if s.NumField() != len(record) {
        return &FieldMismatch{s.NumField(), len(record)}
    }
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        switch f.Type().String() {
        case "string":
            f.SetString(record[i])
        case "int":
            ival, err := strconv.ParseInt(record[i], 10, 0)
            if err != nil {
                return err
            }
            f.SetInt(ival)
        default:
            return &UnsupportedType{f.Type().String()}
        }
    }
    return nil
}

I'll try to create github package is someone needs this implementation.

这篇关于在Go中将CSV记录解组为struct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆