Convert JSON To CSV In Golang with Example

Convert JSON To CSV In Golang with Example

The CSV package has a NewWriter() function that returns the Writer object which is used for writing the CSV data. The csv.Writer() writes csv records that are terminated by the newline and uses the comma as a field delimiter.

Golang csv.NewWriter() is an inbuilt function that converts the data structure into csv format. CSV(Comma Separated Value) is a highly accepted data language, commonly used by Excel and spreadsheets, and as such is very useful if your script is producing data, and you want it in a standard format.

The CSV package has a NewWriter() function that returns the Writer object which is used for writing the CSV data. The csv.Writer() writes csv records that are terminated by the newline and uses the comma as a field delimiter.

See the one by one following code snippets.

Let’s create a json file. We will name it company.json.

[
  { "App": "Instagram", "Company": "Facebook", "Category": "Social Media" },
  { "App": "WeChat", "Company": "Tencent", "Category": "Social Media" },
  { "App": "Hotstar", "Company": "Disney", "Category": "Entertainment" },
  { "App": "CNBC", "Company": "Comcast", "Category": "News" },
  { "App": "SnapChat", "Company": "Snap", "Category": "Social Media" }
]

So, our JSON object has three properties.

  1. App
  2. Company
  3. Category

Now, let’s write the *hello.go *file.

First, we need to import the following go packages.

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

Package csv reads and writes the comma-separated values (CSV) files.

There are many kinds of CSV files and this package supports the format described in RFC 4180.

Package json implements the encoding and decoding of JSON as defined in RFC 7159. The mapping between the JSON and Go values is described in the docs for the Marshal and Unmarshal functions.

Package fmt implements formatted I/O with functions analogous to C’s printf and scanf. The format ‘verbs‘ are derived from C’s but are more straightforward.

Package io/ioutil implements some I/O utility functions.

Package os provides the platform-independent interface to operating system functionality. The design is Unix-like, although an error handling is Go-like; failing calls return values of type error rather than error numbers.

Now, the next step is to define the struct.

// Application struct

type Application struct {
    App      string
    Company  string
    Category string
}

Golang Structs are the user-defined type that contains the collection of named fields/properties. It is used to group related data to form a single unit.

Now, define the main() function.

The first step is to read file using *ioutil.ReadFile() *function.

jsonDataFromFile, err := ioutil.ReadFile("./company.json")

if err != nil {
   fmt.Println(err)
}

We have already defined a json *file—the *ioutil.ReadFile() function reads the file named by filename and returns the contents.

Now, Unmarshal the contents of the json file.

var jsonData []Application
err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

if err != nil {
    fmt.Println(err)
}

Now, create a csv file in Golang using **os.Create() **function.

csvFile, err := os.Create("./data.csv")

if err != nil {
    fmt.Println(err)
}
defer csvFile.Close()

Now, see the following code.

writer := csv.NewWriter(csvFile)

for _, usance := range jsonData {
    var row []string
    row = append(row, usance.App)
    row = append(row, usance.Company)
    row = append(row, usance.Category)
    writer.Write(row)
}

// remember to flush!
writer.Flush()

In the above code snippet, we are creating the writer object and then appending one by one json content to that csv file. So, that json content will be converted into a csv file.

A two-dimensional slice row contains sample csv records. Go os.Create() function creates the csv file data.csv; truncate all it’s records if already exists and returning the instance of os.File() object.

The csvwriter.Write(row) function is called to write each slice of the strings to a file as CSV records.

Our whole final code is the following.

// hello.go

package main

import (
    "encoding/csv"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

// Application struct
type Application struct {
    App      string
    Company  string
    Category string
}

func main() {
    // read data from file
    jsonDataFromFile, err := ioutil.ReadFile("./company.json")

    if err != nil {
        fmt.Println(err)
    }

    // Unmarshal JSON data
    var jsonData []Application
    err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)

    if err != nil {
        fmt.Println(err)
    }

    csvFile, err := os.Create("./data.csv")

    if err != nil {
        fmt.Println(err)
    }
    defer csvFile.Close()

    writer := csv.NewWriter(csvFile)

    for _, usance := range jsonData {
        var row []string
        row = append(row, usance.App)
        row = append(row, usance.Company)
        row = append(row, usance.Category)
        writer.Write(row)
    }

    // remember to flush!
    writer.Flush()
}

Output

Instagram,Facebook,Social Media
WeChat,Tencent,Social Media
Hotstar,Disney,Entertainment
CNBC,Comcast,News
SnapChat,Snap,Social Media

Finally, Golang: Convert JSON to CSV File Example is over.

json go golang

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Golang: How To Convert JSON to Map in Go

How To Convert JSON to Map in Go. Define empty Go map interface and then use the UnMarshal() function to parse JSON to Map which holds the json value.

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

Golang: How To Serialize JSON String in Go Example

Golang json.Marshal() function returns the JSON encoding of interface. Marshal traverses the value of interface recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON.

Handling Null JSON Arrays in Golang (Go)

One of the most frustrating things with Go is how it handles empty arrays when encoding JSON. Rather than returning what is traditionally expected, an empty array, it instead returns null.

Go Tutorial (Golang) - Looping Constructs in Golang | Golang For Loop

In this video we will see the Looping Constructs in Golang. Golang For Loop. Go is an open source programming language which was originally developed by Google. In this Go Tutorial we will Learn Go from the Basics with Code Examples. Go is a statically-typed language.