名前とファイルパスのコレクションを管理するサンプル
プロジェクトの作成
mkdir jsonsaveload
cd jsonsaveload
go mod init example.com/jsonsaveload
ソースコード
ファイル名:jsonsaveload.go
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// Item は名前とファイルパスの組み合わせ
type Item struct {
Name string `json:"name"`
Path string `json:"path"`
}
// Collection は Item のスライス
type Collection []Item
// SaveToFile はJSON形式でコレクションを保存
func (c Collection) SaveToFile(filename string) error {
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
return os.WriteFile(filename, data, 0644)
}
// LoadFromFile はJSONファイルを読み込んでコレクションに変換
func LoadFromFile(filename string) (Collection, error) {
var c Collection
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &c)
return c, err
}
// ダミーデータの作成
func createSampleCollection() Collection {
return Collection{
{Name: "ファイル1", Path: "C:\\test\\file1.txt"},
{Name: "画像A", Path: "D:\\images\\img_a.png"},
{Name: "ドキュメント", Path: "E:\\docs\\doc.pdf"},
}
}
func main() {
jsonFile := filepath.Join(".", "items.json")
collection := createSampleCollection()
if err := collection.SaveToFile(jsonFile); err != nil {
fmt.Println("保存失敗:", err)
return
}
fmt.Println("保存成功:", jsonFile)
loaded, err := LoadFromFile(jsonFile)
if err != nil {
fmt.Println("読み込み失敗:", err)
return
}
fmt.Println("読み込み結果:")
for i, item := range loaded {
fmt.Printf("%d. %s → %s\n", i+1, item.Name, item.Path)
}
}
ビルド
go build
実行
./jsonsaveload.exe
保存成功: items.json
読み込み結果:
1. ファイル1 → C:\test\file1.txt
2. 画像A → D:\images\img_a.png
3. ドキュメント → E:\docs\doc.pdf
実行結果ファイル
ファイル名:items.json
[
{
"name": "ファイル1",
"path": "C:\\test\\file1.txt"
},
{
"name": "画像A",
"path": "D:\\images\\img_a.png"
},
{
"name": "ドキュメント",
"path": "E:\\docs\\doc.pdf"
}
]
コメント