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

How to Efficiently Deserialize CSV Data into Go Structures?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 18:24:12431browse

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

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)
    }
}

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!

Statement:
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