To transform JSON knowledge to a CSV file in Go, that you must create a brand new struct for JSON knowledge, then decode the JSON file into an array of those structs, and eventually save the info from this array as subsequent rows of the CSV file. The 2 most important packages mandatory to do that are encoding/json
to decode the JSON knowledge with the json.Decoder
and encoding/csv
to write down the output CSV knowledge utilizing csv.Author
.
See additionally our examples of how one can convert CSV to JSON and how one can learn CSV file or how one can write knowledge to a CSV file in Go.
Within the instance beneath, we use the knowledge.json
file:
[
{
"vegetable": "carrot",
"fruit": "banana",
"rank": 1
},
{
"vegetable": "potato",
"fruit": "strawberry",
"rank": 2
}
]
Code
|
|
The contents of the output knowledge.csv
file:
vegetable,fruit,rank
carrot,banana,1
potato,strawberry,2
The way it works
- Create a brand new struct for storing learn JSON objects
11 12 13 14 15 16
kind FruitAndVegetableRank struct { // 1. Create a brand new struct for storing learn JSON objects Vegetable string `json:"vegetable"` Fruit string `json:"fruit"` Rank int64 `json:"rank"` }
Step one of JSON to CSV conversion is to load the JSON knowledge to a Go struct. So, we outline a correct kind, with the fields matching the info within the file and annotate them with JSON struct discipline tags to allow JSON decoding into that struct.
- Learn the JSON file into the struct array
19 20 21 22 23 24 25 26 27 28 29 30
// 2. Learn the JSON file into the struct array sourceFile, err := os.Open(supply) if err != nil { return err } // keep in mind to shut the file on the finish of the operate defer sourceFile.Shut() var rating []FruitAndVegetableRank if err := json.NewDecoder(sourceFile).Decode(&rating); err != nil { return err }
We will begin processing our JSON file. We open it (keep in mind to shut the file to launch sources again to the system, for instance, utilizing
defer
key phrase) after which create a brand newjson.Decoder
with this file as an argument. Sincejson.NewDecoder(r io.Reader)
requiresio.Reader
, we don’t must learn the content material of the file beforehand. If we had been to make use of thejson.Unmarshal()
operate, it will be mandatory. WithDecode()
technique, we learn the JSON file and convert it to the slice ofFruitAndVegetableRank
objects. - Create a brand new file to retailer CSV knowledge
32 33 34 35 36 37
// 3. Create a brand new file to retailer CSV knowledge outputFile, err := os.Create(vacation spot) if err != nil { return err } defer outputFile.Shut()
The CSV knowledge will probably be saved to a file, so on this step, we create a brand new
vacation spot
file in a reasonably customary approach. - Write the header of the CSV file and the successive rows by iterating via the JSON struct array
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
// 4. Write the header of the CSV file and the successive rows by iterating via the JSON struct array author := csv.NewWriter(outputFile) defer author.Flush() header := []string{"vegetable", "fruit", "rank"} if err := author.Write(header); err != nil { return err } for _, r := vary rating { var csvRow []string csvRow = append(csvRow, r.Vegetable, r.Fruit, fmt.Dash(r.Rank)) if err := author.Write(csvRow); err != nil { return err } }
Because the final step, we create a brand new
csv.Author
that writes the info in CSV format to the output file. Keep in mind to nameauthor.Flush
to make sure that all of the buffered content material is written earlier than the operate finishes. The writing course of consists of iterating via the array ofFruitAndVegetableRank
objects and making a CSV row for every of them. Then, This row is saved utilizingauthor.Write()
technique. Within the instance, we additionally wrote the header row as the primary line of the file.