How to convert a JSON file to CSV file with Golang

Carlos Armando Marcano Vargas
2 min readDec 7, 2021

Many times I wanted to store the data from an API and look at it in another moment and don’t call the API every time.

I spent almost a whole week trying to build this program. This is a program to practice Golang and its standard library. I learn a lot in the process, I hope you do too.

This is the data we will convert:

{ "genus": "Malus", 
"name": "Apple",
"id": 6,
"family": "Rosaceae",
"order": "Rosales",
"nutrition":
{ "carbohydrates": 11.4,
"protein": 0.3,
"fat": 0.4,
"calories": 52,
"sugar": 10.3 }
}

This is the code:

package mainimport (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"encoding/csv"
"encoding/json"
)
func main() { // This line use the HTTP package to call the API
// and store the data in a variable.
response,err := http.Get("https://www.fruityvice.com/api/fruit/apple" ) if err != nil {
fmt.Print(err.Error())
os.Exit(1)
}
// This code reads the data stores it in the variable. responseData, err := ioutil.ReadAll(response.Body) if err != nil {
log.Fatal(err)
}
// This code create a Map
//because the json file has different types of values we use "interface{}".
var fruitObject map[string]interface{}
err = json.Unmarshal([]byte(responseData), &fruitObject)
if err != nil {
fmt.Println(err)
}
// This code use "os" package to create the csv file inside the same directory. csvFile, err := os.Create("./fruits.csv") if err != nil {
fmt.Println(err)
}
defer csvFile.Close() // This code close the file.
//This code use enconding/csv package to write the csv file. writer := csv.NewWriter(csvFile) //This code loop through the interface and store the data
//in a slice. The "enconding/csv" package only writes in []string.
for k,v := range fruitObject {
var row []string
var b string
//This code use switch to check if the values are strings
// if is not, it will convert it to a string using string formatting(fmt.Sprintf).
switch elemTyped := v.(type) {
case int:
a := fmt.Sprintf("%0.1f", elemTyped)
row = append(row, a)
case float64:
a := fmt.Sprintf("%0.1f", elemTyped)
row = append(row, a)
case string:
b = elemTyped
row = append(row, b)
case interface {}:
c := fmt.Sprintf("%v", elemTyped)
row = append(row, c)
}
//This code write the data of variable row into a csv file.
writer.Write(row)
}
//This code ensure all buffered data is written
//in the file before closing the file.
writer.Flush() fmt.Println("csv file created")
}

Follow me on Twitter.

--

--

Carlos Armando Marcano Vargas

I'm self taught developer. I like to write about what I'm learning, and building. Always writting about Python, Go and Rust.