0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

こちらのプログラムをリートンで変換しました。
Python3: ヘッダーを考慮した csv ファイルの読み込み

プログラム

csv_header.go
package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"os"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Println("Usage: go run csv_to_json.go <input_csv_file> <output_json_file>")
		return
	}

	inputCSVFile := os.Args[1]
	outputJSONFile := os.Args[2]

	// Open the CSV file
	csvFile, err := os.Open(inputCSVFile)
	if err != nil {
		fmt.Println("Error opening CSV file:", err)
		return
	}
	defer csvFile.Close()

	// Create a CSV reader
	csvReader := csv.NewReader(csvFile)
	header, err := csvReader.Read()
	if err != nil {
		fmt.Println("Error reading CSV header:", err)
		return
	}

	// Read CSV data into a slice of maps
	var records []map[string]string
	for {
		row, err := csvReader.Read()
		if err != nil {
			break
		}
		rowMap := make(map[string]string)
		for i, field := range row {
			rowMap[header[i]] = field
		}
		records = append(records, rowMap)
	}

	// Convert CSV data to JSON
	jsonData, err := json.Marshal(records)
	if err != nil {
		fmt.Println("Error converting to JSON:", err)
		return
	}

	// Write JSON data to output file
	err = os.WriteFile(outputJSONFile, jsonData, 0644)
	if err != nil {
		fmt.Println("Error writing JSON file:", err)
		return
	}

	fmt.Println("CSV to JSON conversion completed successfully.")
}

実行

go run csv_header.go cities_header.csv cities.json
go run csv_header.go cities_ex02.csv cities_ex02.json

確認したバージョン

$ go version
go version go1.22.2 linux/amd64
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?