Convert JSON To CSV In Golang with Example

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

Convert JSON To CSV In Golang with Example
32.40 GEEK