Convert-JSON-API-to-CSV-Golang
Here you will find a easy program to convert a JSON response API to a CSV File
Packages required
No need to install any package explictly. Just copy paste the follwoing import in main() of main.go.
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
Reading from a JSON response API
url := "http://localhost:3000/orderdata"
spaceClient := http.Client{
Timeout: time.Second * 2,
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "spacecount-tutorial")
res, getErr := spaceClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
Order := Orders{}
jsonErr := json.Unmarshal(body, &Order)
if jsonErr != nil {
log.Fatal(jsonErr)
}
fmt.Println("Successfully read JSON API")
Reading from a JSON response File
jsonFile, err := os.Open("OrderDetails.json")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened OrderDetails.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var Order Orders
err = json.Unmarshal(byteValue, &Order)
if err != nil {
fmt.Println(err)
}
Creating Writing to a CSV File
csvFile, err := os.Create("./OrderDetails.csv")
if err != nil {
fmt.Println(err)
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
var row []string
row = append(row, Order.OrdersummaryBySupplierid.Supplier.City)
row = append(row, Order.OrdersummaryBySupplierid.Supplier.Name)
row = append(row, Order.OrdersummaryBySupplierid.Supplier.State)
writer.Write(row)
for _, emp := range Order.OrdersummaryBySupplierid.Orderstatus {
var row1 []string
row1 = append(row1, emp.Orderdate)
row1 = append(row1, emp.Billed)
row1 = append(row1, emp.Bounced)
row1 = append(row1, emp.Pending)
writer.Write(row1)
}
writer.Flush()
Note
You can change the delimeter '|' of .csv format by ctrl + Click on writer.Write() function
Connect
Shubham Snehi