How to Convert CSV to JSON using Go

Cloudmersive
2 min readOct 31, 2022

--

Converting between common data formats is a persistent need for developers everywhere. Thankfully, with our Document Conversion API endpoint, you can easily convert between dozens of common/important data types for free, using ready-to-run, complementary code examples from our API console to call each API iteration.

Below, I’ve provided code examples in Go to help you take advantage of our CSV to JSON conversion API iteration. All you’ll need in addition to these examples is a Cloudmersive API key, which you can get for free (with a limit of 800 API calls per month & no additional commitments) by registering a free account on our website.

To call the API, simply copy the below code examples into your file, and include your CSV file & API key inputs in the appropriate fields:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/convert/csv/to/json"
method := "POST"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("columnNamesFromFirstRow", "<boolean>")
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}

It’s important to note that by default, this API will use the first rows from your CSV file as labels for the columns. You can change this (to set column names like ColumnO, Column1, etc.) by setting the colunmNamesFromFirstRow boolean to “False.”

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet