[encoding/json] How to Convert JSON to CSV
사용법 정리
- encoding/csv
- encoding/json
- io/ioutil
[
{ "App": "Instagram", "Company": "Facebook", "Category": "Social Media" },
{ "App": "WeChat", "Company": "Tencent", "Category": "Social Media" },
{ "App": "Hotstar", "Company": "Disney", "Category": "Entertainment" },
{ "App": "CNBC", "Company": "Comcast", "Category": "News" },
{ "App": "SnapChat", "Company": "Snap", "Category": "Social Media" }
]
So, our JSON object has three properties.
App
Company
Category
Now, let’s write the hello.go file.
First, we need to import the following go packages.
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
// Application struct
type Application struct {
App string
Company string
Category string
}
jsonDataFromFile, err := ioutil.ReadFile("./company.json")
if err != nil {
fmt.Println(err)
}
var jsonData []Application
err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)
if err != nil {
fmt.Println(err)
}
csvFile, err := os.Create("./data.csv")
if err != nil {
fmt.Println(err)
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
for _, usance := range jsonData {
var row []string
row = append(row, usance.App)
row = append(row, usance.Company)
row = append(row, usance.Category)
writer.Write(row)
}
// remember to flush!
writer.Flush()
// hello.go
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
// Application struct
type Application struct {
App string
Company string
Category string
}
func main() {
// read data from file
jsonDataFromFile, err := ioutil.ReadFile("./company.json")
if err != nil {
fmt.Println(err)
}
// Unmarshal JSON data
var jsonData []Application
err = json.Unmarshal([]byte(jsonDataFromFile), &jsonData)
if err != nil {
fmt.Println(err)
}
csvFile, err := os.Create("./data.csv")
if err != nil {
fmt.Println(err)
}
defer csvFile.Close()
writer := csv.NewWriter(csvFile)
for _, usance := range jsonData {
var row []string
row = append(row, usance.App)
row = append(row, usance.Company)
row = append(row, usance.Category)
writer.Write(row)
}
// remember to flush!
writer.Flush()
}
Output
Instagram,Facebook,Social Media
WeChat,Tencent,Social Media
Hotstar,Disney,Entertainment
CNBC,Comcast,News
SnapChat,Snap,Social Media
출처 https://appdividend.com/2020/03/09/how-to-convert-json-to-csv-in-golang-example/
Author And Source
이 문제에 관하여([encoding/json] How to Convert JSON to CSV), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@james-chun-dev/encodingjson-How-to-Convert-JSON-to-CSV저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)