Home > Mobile >  gocsv UnmarshalBytes fail
gocsv UnmarshalBytes fail

Time:11-19

When I call the following function, I get err parse error on line 2, column 25: bare " in non-quoted-field Can you tell me why this is happening? How do I fix it?

func ParseFromCSV(data []byte, obj interface{}) error {
    encode := GetEncode(data)
    if encode == GBK {
        var err error
        data, err = ConvertGBK2UTF8(data)
        if err != nil {
            return err
        }
    }
    bom := []byte{0xEF, 0xBB, 0xBF}

    if len(data) > len(bom) && data[0] == bom[0] && data[1] == bom[1] && data[2] == bom[2] {
        data = data[3:]
    }
    
    if err := gocsv.UnmarshalBytes(data, obj); err != nil { // Load clie
        fmt.Println(err) // nts from file
        return err
    }
    return nil
}

CodePudding user response:

There is an solved issue on the gocsv github. The user reports the exact same issue, likely due to UTF-8 BOM encoding.

Replacing

if err := gocsv.UnmarshalBytes(data, obj); err != nil { // Load clie
    fmt.Println(err) // nts from file
    return err
}

with

in := csv.NewReader(transform.NewReader(bytes.NewReader(data), unicode.UTF8BOM.NewDecoder()))
if err := gocsv.UnmarshalCSV(in, obj); err != nil { // Load clie
    fmt.Println(err) // nts from file
    return err
}

should fix it.

  • Related