← Runnable Projects

阅读中文版本

JSON Array to CSV Converter

A Node CLI that converts an array of flat JSON objects to CSV with a stable column order and correct quoting of commas, quotes, and newlines.

beginnerjavascriptunverified

Project

node-json-to-csv

Entry point: json-to-csv.mjs

Install

node --version

Run

node json-to-csv.mjs rows.json

Test

node --test json-to-csv.test.mjs

Expected output

Writes a CSV with a header row and one row per object, quoting any field containing a comma, quote, or newline.

Dependencies

  • node >=20

What it does

Unions the keys of every object to build a stable header, then writes each row with RFC 4180 quoting. Fields with a comma, a quote, or a newline are wrapped in quotes and inner quotes are doubled.

import { readFileSync } from 'node:fs';

const escapeField = (value) => {
  const s = value == null ? '' : String(value);
  return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
};

export function toCsv(rows) {
  const columns = [...new Set(rows.flatMap((r) => Object.keys(r)))];
  const lines = [columns.join(',')];
  for (const row of rows) lines.push(columns.map((c) => escapeField(row[c])).join(','));
  return lines.join('\n');
}

const rows = JSON.parse(readFileSync(process.argv[2], 'utf8'));
if (!Array.isArray(rows)) { console.error('input must be a JSON array'); process.exit(1); }
process.stdout.write(toCsv(rows) + '\n');

Run and verify

node json-to-csv.mjs rows.json

Run the test command to check the implementation: node --test json-to-csv.test.mjs.

Expected Output

For [{“name”:“Ada”,“note”:“a, b”},{“name”:“Lin”,“note”:“ok”}] the output quotes the comma-containing field:

name,note
Ada,"a, b"
Lin,ok

Limitations

Handles flat objects only; nested values are stringified as [object Object]. Choose a flattening rule before using it with hierarchical data.