How to Convert JSON to CSV in Golang

To convert JSON to CSV in Golang, decode the JSON data with the json.Decoder and encoding/csv package to write the output CSV data using csv.Writer.

First, you will need to unmarshal the JSON data into a suitable data structure (like a slice of structs or a slice of maps), and then you can write that data to a CSV file using the csv.Writer type.


package main

import (

// Define a struct to represent a person
type Person struct {
  Name string `json:"name"`
  Age int `json:"age"`
  Gender string `json:"gender"`

func main() {
  // Sample JSON data
  jsonData := `[
    {"name": "Krunal", "age": 30, "gender": "male"},
    {"name": "Ankit", "age": 25, "gender": "male"},
    {"name": "JK", "age": 33, "gender": "female"}

  // Unmarshal the JSON data into a slice of Person structs
  var people []Person
  err := json.Unmarshal([]byte(jsonData), &people)
  if err != nil {
    log.Fatalf("Error unmarshaling JSON: %v", err)

  // Create a CSV file
  csvFile, err := os.Create("people.csv")
  if err != nil {
    log.Fatalf("Error creating CSV file: %v", err)
  defer csvFile.Close()

  // Create a CSV writer and write the header
  csvWriter := csv.NewWriter(csvFile)
  header := []string{"Name", "Age", "Gender"}
  err = csvWriter.Write(header)
  if err != nil {
    log.Fatalf("Error writing CSV header: %v", err)

  // Write the data to the CSV file
  for _, person := range people {
    record := []string{person.Name, fmt.Sprint(person.Age), person.Gender}
    err = csvWriter.Write(record)
    if err != nil {
      log.Fatalf("Error writing CSV record: %v", err)

 // Flush the CSV writer to ensure all data is written to the file
  err = csvWriter.Error()
  if err != nil {
    log.Fatalf("Error flushing CSV writer: %v", err)

  fmt.Println("Successfully converted JSON to CSV")


The “people.csv” file looks like one e below.


In this code, we defined a Person struct with Name, Age, and Gender fields.

In the next step, we provided sample JSON data and unmarshal it into a slice of Person structs using “json.Unmarshal()”. After that, we created a CSV file called “people.csv” and a CSV writer using “csv.NewWriter()”.

We wrote the header and the data to the CSV file and called “csvWriter.Flush()” to ensure all the data was written to the file.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.