[encoding/json] How to Convert JSON to CSV

천현철·2021년 6월 6일
0

Golang

목록 보기
5/13

사용법 정리

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

profile
기도하지말고 행동하라

2개의 댓글

comment-user-thumbnail
2023년 9월 15일

The road to business success is paved with effective advertising strategies that capture attention, build brand awareness, and drive conversions. The journey businesses on https://www.adpremiumsunlimited.com/ undertake to achieve success through advertising.

답글 달기
comment-user-thumbnail
2023년 9월 15일

The moving company is liable for the replacement or repair of damaged or lost items at their current market value. While this https://www.themobilestorageguy.com/ option provides more extensive coverage, it typically comes with an additional fee.

답글 달기