[encoding/json] How to Convert JSON to CSV

3369 단어 golanggolang

사용법 정리

  • 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/

좋은 웹페이지 즐겨찾기