Thursday, April 25, 2024
HomeGolangConvert JSON to CSV in Go (Golang)

Convert JSON to CSV in Go (Golang)



To transform JSON knowledge to a CSV file in Go, that you must create a brand new struct for JSON knowledge, then decode the JSON file into an array of those structs, and eventually save the info from this array as subsequent rows of the CSV file. The 2 most important packages mandatory to do that are encoding/json to decode the JSON knowledge with the json.Decoder and encoding/csv to write down the output CSV knowledge utilizing csv.Author.

See additionally our examples of how one can convert CSV to JSON and how one can learn CSV file or how one can write knowledge to a CSV file in Go.

Within the instance beneath, we use the knowledge.json file:

[
    {
        "vegetable": "carrot",
        "fruit": "banana",
        "rank": 1
    },
    {
        "vegetable": "potato",
        "fruit": "strawberry",
        "rank": 2
    }
]

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
bundle most important

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "log"
    "os"
)

kind FruitAndVegetableRank struct {
    // 1. Create a brand new struct for storing learn JSON objects
    Vegetable string `json:"vegetable"`
    Fruit     string `json:"fruit"`
    Rank      int64  `json:"rank"`
}

func convertJSONToCSV(supply, vacation spot string) error {
    // 2. Learn the JSON file into the struct array
    sourceFile, err := os.Open(supply)
    if err != nil {
        return err
    }
    // keep in mind to shut the file on the finish of the operate
    defer sourceFile.Shut()

    var rating []FruitAndVegetableRank
    if err := json.NewDecoder(sourceFile).Decode(&rating); err != nil {
        return err
    }

    // 3. Create a brand new file to retailer CSV knowledge
    outputFile, err := os.Create(vacation spot)
    if err != nil {
        return err
    }
    defer outputFile.Shut()

    // 4. Write the header of the CSV file and the successive rows by iterating via the JSON struct array
    author := csv.NewWriter(outputFile)
    defer author.Flush()

    header := []string{"vegetable", "fruit", "rank"}
    if err := author.Write(header); err != nil {
        return err
    }

    for _, r := vary rating {
        var csvRow []string
        csvRow = append(csvRow, r.Vegetable, r.Fruit, fmt.Dash(r.Rank))
        if err := author.Write(csvRow); err != nil {
            return err
        }
    }
    return nil
}

func most important() {
    if err := convertJSONToCSV("knowledge.json", "knowledge.csv"); err != nil {
        log.Deadly(err)
    }
}

The contents of the output knowledge.csv file:

vegetable,fruit,rank
carrot,banana,1
potato,strawberry,2

The way it works

  1. Create a brand new struct for storing learn JSON objects
    11
    12
    13
    14
    15
    16
    
    kind FruitAndVegetableRank struct {
        // 1. Create a brand new struct for storing learn JSON objects
        Vegetable string `json:"vegetable"`
        Fruit     string `json:"fruit"`
        Rank      int64  `json:"rank"`
    }
    

    Step one of JSON to CSV conversion is to load the JSON knowledge to a Go struct. So, we outline a correct kind, with the fields matching the info within the file and annotate them with JSON struct discipline tags to allow JSON decoding into that struct.

  2. Learn the JSON file into the struct array
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    
    // 2. Learn the JSON file into the struct array
    sourceFile, err := os.Open(supply)
    if err != nil {
        return err
    }
    // keep in mind to shut the file on the finish of the operate
    defer sourceFile.Shut()
    
    var rating []FruitAndVegetableRank
    if err := json.NewDecoder(sourceFile).Decode(&rating); err != nil {
        return err
    }
    

    We will begin processing our JSON file. We open it (keep in mind to shut the file to launch sources again to the system, for instance, utilizing defer key phrase) after which create a brand new json.Decoder with this file as an argument. Since json.NewDecoder(r io.Reader) requires io.Reader, we don’t must learn the content material of the file beforehand. If we had been to make use of the json.Unmarshal() operate, it will be mandatory. With Decode() technique, we learn the JSON file and convert it to the slice of FruitAndVegetableRank objects.

  3. Create a brand new file to retailer CSV knowledge
    32
    33
    34
    35
    36
    37
    
    // 3. Create a brand new file to retailer CSV knowledge
    outputFile, err := os.Create(vacation spot)
    if err != nil {
        return err
    }
    defer outputFile.Shut()
    

    The CSV knowledge will probably be saved to a file, so on this step, we create a brand new vacation spot file in a reasonably customary approach.

  4. Write the header of the CSV file and the successive rows by iterating via the JSON struct array
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    
    // 4. Write the header of the CSV file and the successive rows by iterating via the JSON struct array
    author := csv.NewWriter(outputFile)
    defer author.Flush()
    
    header := []string{"vegetable", "fruit", "rank"}
    if err := author.Write(header); err != nil {
        return err
    }
    
    for _, r := vary rating {
        var csvRow []string
        csvRow = append(csvRow, r.Vegetable, r.Fruit, fmt.Dash(r.Rank))
        if err := author.Write(csvRow); err != nil {
            return err
        }
    }
    

    Because the final step, we create a brand new csv.Author that writes the info in CSV format to the output file. Keep in mind to name author.Flush to make sure that all of the buffered content material is written earlier than the operate finishes. The writing course of consists of iterating via the array of FruitAndVegetableRank objects and making a CSV row for every of them. Then, This row is saved utilizing author.Write() technique. Within the instance, we additionally wrote the header row as the primary line of the file.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments