To transform CSV knowledge to JSON in Go, you need to comply with these steps:
- Create a struct for storing CSV traces and annotate it with JSON struct discipline tags.
- Learn CSV file utilizing
csv.Reader
. - Assign successive traces of uncooked CSV knowledge to situations of the created struct.
- Convert an array of structs to JSON utilizing marshaling capabilities from the
encoding/json
bundle.
Within the instance beneath, we use
knowledge.csv
file:greens,fruits,rank carrot,banana,1 potato,strawberry,2
See additionally our examples of methods to convert JSON to CSV and methods to learn CSV file or methods to write knowledge to a CSV file in Go
bundle essential
import (
"encoding/csv"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
)
sort ShoppingRecord struct {
// 1. Create a struct for storing CSV traces and annotate it with JSON struct discipline tags
Vegetable string `json:"vegetable"`
Fruit string `json:"fruit"`
Rank int `json:"rank"`
}
func createShoppingList(knowledge [][]string) []ShoppingRecord {
// convert csv traces to array of structs
var shoppingList []ShoppingRecord
for i, line := vary knowledge {
if i > 0 { // omit header line
var rec ShoppingRecord
for j, discipline := vary line {
if j == 0 {
rec.Vegetable = discipline
} else if j == 1 {
rec.Fruit = discipline
} else if j == 2 {
var err error
rec.Rank, err = strconv.Atoi(discipline)
if err != nil {
proceed
}
}
}
shoppingList = append(shoppingList, rec)
}
}
return shoppingList
}
func essential() {
// open file
f, err := os.Open("knowledge.csv")
if err != nil {
log.Deadly(err)
}
// keep in mind to shut the file on the finish of this system
defer f.Shut()
// 2. Learn CSV file utilizing csv.Reader
csvReader := csv.NewReader(f)
knowledge, err := csvReader.ReadAll()
if err != nil {
log.Deadly(err)
}
// 3. Assign successive traces of uncooked CSV knowledge to fields of the created structs
shoppingList := createShoppingList(knowledge)
// 4. Convert an array of structs to JSON utilizing marshaling capabilities from the encoding/json bundle
jsonData, err := json.MarshalIndent(shoppingList, "", " ")
if err != nil {
log.Deadly(err)
}
fmt.Println(string(jsonData))
}
Output:
[
{
"vegetable": "carrot",
"fruit": "banana",
"rank": 1
},
{
"vegetable": "potato",
"fruit": "strawberry",
"rank": 2
}
]