Home > Backend Development > Golang > How to Efficiently Deserialize CSV Data into Go Structures?

How to Efficiently Deserialize CSV Data into Go Structures?

Susan Sarandon
Release: 2024-12-02 18:24:12
Original
429 people have browsed it

How to Efficiently Deserialize CSV Data into Go Structures?

Question:

How can I efficiently deserialize CSV records into Go structures?

Problem Statement:

Suppose you have a custom Go structure Test, with fields Name, Surname, and Age. You have a CSV file containing records in the format:

John;Smith;42
Piter;Abel;50
Copy after login

How can you automatically unmarshal these records into instances of the Test structure, without relying on manual deserialization operations?

Answer:

To simplify the deserialization process, consider using the gocarina/gocsv library. gocsv offers similar functionality to the encoding/json package but specifically caters to CSV data.

Here's an example using gocsv:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/gocarina/gocsv"
)

type Test struct {
    Name    string `csv:"Name"`
    Surname string `csv:"Surname"`
    Age     int    `csv:"Age"`
}

func main() {
    // Open CSV file for reading
    in, err := os.Open("test.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer in.Close()

    // Declare a slice to hold the Test structures
    var tests []Test

    // Unmarshal the CSV records into the Test structures
    if err := gocsv.UnmarshalFile(in, &tests); err != nil {
        log.Fatal(err)
    }

    // Print the unmarshaled data
    for _, test := range tests {
        fmt.Printf("Name: %s, Surname: %s, Age: %d\n", test.Name, test.Surname, test.Age)
    }
}
Copy after login

In this example, gocsv handles the deserialization process for you, simplifying the conversion of CSV records into Go structures. You can use custom field tags in the Test struct to specify the CSV column headers for each field, ensuring accurate mapping.

The above is the detailed content of How to Efficiently Deserialize CSV Data into Go Structures?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template