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?

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

準備

npm install --save csv-parser

確認したバージョン

$ node --version
v22.3.0

プログラム

csv_header.js
#! /usr/bin/env node

// csv_header.js

const fs = require('fs');
const csv = require('csv-parser');

// Function to write to a file
function fileWriteProc(fileName, strOut) {
    fs.writeFileSync(fileName, strOut);
}

// Command line arguments
const args = process.argv.slice(2);
const fileCsv = args[0];
const fileJson = args[1];

// Read CSV file
const rows = [];
fs.createReadStream(fileCsv)
    .pipe(csv())
    .on('data', (row) => {
        rows.push(row);
    })
    .on('end', () => {
        // Convert rows to JSON string
        const outStr = JSON.stringify(rows);
        
        // Write JSON string to file
        fileWriteProc(fileJson, outStr);

        console.log(`Conversion successful. JSON data written to ${fileJson}`);
    });

実行方法

./csv_header.js cities_header.csv cities.json
./csv_header.js cities_ex02.csv cities_ex02.json
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?