iTranslated by AI
Exporting Zaim Data to CSV Using the Zaim API and Go
This is the Go version of my previously posted article, "Outputting Zaim Data to CSV Using Zaim API and Python".
Purpose
- Create a system to export Zaim data to CSV.
- Ensure the backup data contains the same content as the file exported by Zaim's own export function (aligning the column names).
Procedure
API Registration and Token Acquisition
For API registration and token acquisition, please refer to the previous article.
Implementing the Code
Add a package to fetch and manipulate Zaim data
go get github.com/s-sasaki-0529/go-zaim
Add Code to Fetch Data
Add the Acquired Token Information to the .env File
Create a .env file and enter the acquired tokens.
CONSUMER_KEY=
CONSUMER_SECRET=
ACCESS_TOKEN=
ACCESS_SECRET=
Add Code to Fetch Data
Implement config.go to load token information, zaim.go to fetch data, and main.go to call each process.
package main
import (
"fmt"
"os"
gozaim "github.com/s-sasaki-0529/go-zaim"
"github.com/joho/godotenv"
)
func GetClient() *gozaim.Client {
err := godotenv.Load(".env")
if err != nil {
fmt.Printf("Could not load: %v", err)
}
c := gozaim.NewClient(
os.Getenv("CONSUMER_KEY"),
os.Getenv("CONSUMER_SECRET"),
os.Getenv("ACCESS_TOKEN"),
os.Getenv("ACCESS_SECRET"),
)
return c
}
package main
import (
"fmt"
"net/url"
gozaim "github.com/s-sasaki-0529/go-zaim"
)
type ZaimData struct {
money []gozaim.Money
categories []gozaim.Category
genres []gozaim.Genre
accounts []gozaim.Account
}
// Fetch Zaim data
func GetZaimData(c *gozaim.Client) ZaimData {
// Fetch data list
m, err := c.FetchMoney(url.Values{})
if err != nil {
fmt.Println("Failed to get money", err)
}
msg := fmt.Sprintf("Fetched %d records.\n", len(m))
fmt.Println(msg)
// Fetch category list
ca, err := c.FetchCategories()
if err != nil {
fmt.Println("Failed to get categories", err)
}
// Fetch genre list
g, err := c.FetchGenres()
if err != nil {
fmt.Println("Failed to get genres", err)
}
// Fetch account list
a, err := c.FetchAccounts()
if err != nil {
fmt.Println("Failed to get accounts", err)
}
result := ZaimData{
m,
ca,
g,
a,
}
return result
}
package main
import "fmt"
func main() {
// Client settings
c := GetClient()
// Fetch data
d := GetZaimData(c)
fmt.Println(d)
}
Data has been fetched, but items like categories and accounts only contain IDs. Therefore, we will implement a process to assign various names based on the IDs.
Assign Names Based on IDs
Add the process for assigning names.
type MoneyJP struct {
Date string `csv:"日付"`
Mode string `csv:"方法"`
Category string `csv:"カテゴリ"`
Genre string `csv:"カテゴリの内訳"`
From string `csv:"支払元"`
To string `csv:"入金先"`
Name string `csv:"品目"`
Comment string `csv:"メモ"`
Place string `csv:"お店"`
CurrencyCode string `csv:"通貨"`
Income int `csv:"収入"`
Payment int `csv:"支出"`
Transfer int `csv:"振替"`
}
// Assign type names based on type IDs
func ConvertData(datas ZaimData) []MoneyJP {
var money []MoneyJP
for _, v := range datas.money {
p, i, t := GetAmount(v.Mode, v.Amount)
cm := MoneyJP{
v.Date,
v.Mode,
GetCategoryName(v.CategoryID, datas.categories),
GetGenreName(v.GenreID, datas.genres),
GetAccountName(v.FromAccountID, datas.accounts),
GetAccountName(v.ToAccountID, datas.accounts),
v.Name,
v.Comment,
v.Place,
v.CurrencyCode,
p,
i,
t,
}
money = append(money, cm)
}
return money
}
// Returns the category name associated with the ID
func GetCategoryName(id int, categories []gozaim.Category) string {
for _, v := range categories {
if v.ID == id {
return v.Name
}
}
return ""
}
// Returns the genre name associated with the ID
func GetGenreName(id int, genres []gozaim.Genre) string {
for _, v := range genres {
if v.ID == id {
return v.Name
}
}
return ""
}
// Returns the account name associated with the ID
func GetAccountName(id int, accounts []gozaim.Account) string {
for _, v := range accounts {
if v.ID == id {
return v.Name
}
}
return "-"
}
// Returns the amount according to the mode
func GetAmount(mode string, amount int) (int, int, int) {
var p, i, t int
switch mode {
case "payment":
p = amount
case "income":
i = amount
case "transfer":
t = amount
default:
}
return p, i, t
}
// Assign type names
cd := ConvertData(d)
fmt.Println(cd)
Next, we will implement the process of changing the column names to Japanese and outputting to CSV.
Add Code to Output Data
We will change the column names to Japanese and remove unnecessary data such as user IDs. Then, we will export the organized data to CSV.
// CSV output
func OutputCSV(money []MoneyJP) {
file, _ := os.OpenFile("zaim-backup.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
defer file.Close()
// Write the CSV file
gocsv.MarshalFile(&money, file)
}
// Output to CSV
OutputCSV(cd)
With this, the code implementation is complete.
Execute the Implemented Code
Run the following command in an application that can execute shell scripts, such as a terminal.
% go run *.go
The number of fetched records will be displayed in the console, and a file named zaim-backup.csv will be generated.
Summary
The code implemented this time is available in the following repository.
References
Discussion