|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useMemo, useState } from "react"; |
| 4 | +import { useTranslations } from "next-intl"; |
| 5 | + |
| 6 | +// RFC 4180 compliant CSV parser (handles quoted fields with commas, escaped quotes, line breaks). |
| 7 | +function parseCsv(text: string, delimiter: string): string[][] { |
| 8 | + const rows: string[][] = []; |
| 9 | + let row: string[] = []; |
| 10 | + let field = ""; |
| 11 | + let inQuotes = false; |
| 12 | + let i = 0; |
| 13 | + while (i < text.length) { |
| 14 | + const ch = text[i]; |
| 15 | + if (inQuotes) { |
| 16 | + if (ch === '"') { |
| 17 | + if (text[i + 1] === '"') { |
| 18 | + field += '"'; |
| 19 | + i += 2; |
| 20 | + continue; |
| 21 | + } |
| 22 | + inQuotes = false; |
| 23 | + i++; |
| 24 | + continue; |
| 25 | + } |
| 26 | + field += ch; |
| 27 | + i++; |
| 28 | + } else { |
| 29 | + if (ch === '"') { |
| 30 | + inQuotes = true; |
| 31 | + i++; |
| 32 | + } else if (ch === delimiter) { |
| 33 | + row.push(field); |
| 34 | + field = ""; |
| 35 | + i++; |
| 36 | + } else if (ch === "\n" || ch === "\r") { |
| 37 | + row.push(field); |
| 38 | + rows.push(row); |
| 39 | + row = []; |
| 40 | + field = ""; |
| 41 | + if (ch === "\r" && text[i + 1] === "\n") i += 2; |
| 42 | + else i++; |
| 43 | + } else { |
| 44 | + field += ch; |
| 45 | + i++; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + if (field || row.length) { |
| 50 | + row.push(field); |
| 51 | + rows.push(row); |
| 52 | + } |
| 53 | + return rows.filter((r) => r.length > 1 || (r.length === 1 && r[0] !== "")); |
| 54 | +} |
| 55 | + |
| 56 | +function escapeCsvField(value: unknown, delimiter: string): string { |
| 57 | + const s = value === null || value === undefined ? "" : String(value); |
| 58 | + if (s.includes(delimiter) || s.includes('"') || s.includes("\n") || s.includes("\r")) { |
| 59 | + return '"' + s.replace(/"/g, '""') + '"'; |
| 60 | + } |
| 61 | + return s; |
| 62 | +} |
| 63 | + |
| 64 | +export default function CsvJsonConverter() { |
| 65 | + const t = useTranslations("tools.csv-json-converter"); |
| 66 | + const [direction, setDirection] = useState<"csvToJson" | "jsonToCsv">("csvToJson"); |
| 67 | + const [delimiter, setDelimiter] = useState(","); |
| 68 | + const [headerRow, setHeaderRow] = useState(true); |
| 69 | + const [input, setInput] = useState( |
| 70 | + "name,age,city\nAlice,30,Tokyo\nBob,25,Seoul\nCarol,42,Madrid" |
| 71 | + ); |
| 72 | + |
| 73 | + const result = useMemo(() => { |
| 74 | + if (!input.trim()) return null; |
| 75 | + try { |
| 76 | + if (direction === "csvToJson") { |
| 77 | + const rows = parseCsv(input, delimiter); |
| 78 | + if (rows.length === 0) return { ok: true as const, value: "[]" }; |
| 79 | + if (headerRow) { |
| 80 | + const headers = rows[0]!; |
| 81 | + const data = rows.slice(1).map((r) => { |
| 82 | + const obj: Record<string, string> = {}; |
| 83 | + for (let i = 0; i < headers.length; i++) { |
| 84 | + const key = headers[i]!; |
| 85 | + obj[key] = r[i] ?? ""; |
| 86 | + } |
| 87 | + return obj; |
| 88 | + }); |
| 89 | + return { ok: true as const, value: JSON.stringify(data, null, 2) }; |
| 90 | + } |
| 91 | + return { ok: true as const, value: JSON.stringify(rows, null, 2) }; |
| 92 | + } else { |
| 93 | + const data: unknown = JSON.parse(input); |
| 94 | + if (!Array.isArray(data)) throw new Error("expected an array of objects or arrays"); |
| 95 | + if (data.length === 0) return { ok: true as const, value: "" }; |
| 96 | + // Decide if array-of-objects or array-of-arrays |
| 97 | + if (typeof data[0] === "object" && data[0] !== null && !Array.isArray(data[0])) { |
| 98 | + const headers = [...new Set(data.flatMap((r) => Object.keys(r as object)))]; |
| 99 | + const lines = [headers.map((h) => escapeCsvField(h, delimiter)).join(delimiter)]; |
| 100 | + for (const row of data) { |
| 101 | + const r = row as Record<string, unknown>; |
| 102 | + lines.push(headers.map((h) => escapeCsvField(r[h], delimiter)).join(delimiter)); |
| 103 | + } |
| 104 | + return { ok: true as const, value: lines.join("\n") }; |
| 105 | + } |
| 106 | + // Array of arrays |
| 107 | + const lines = (data as unknown[][]).map((row) => row.map((v) => escapeCsvField(v, delimiter)).join(delimiter)); |
| 108 | + return { ok: true as const, value: lines.join("\n") }; |
| 109 | + } |
| 110 | + } catch (err) { |
| 111 | + return { ok: false as const, error: (err as Error).message }; |
| 112 | + } |
| 113 | + }, [direction, input, delimiter, headerRow]); |
| 114 | + |
| 115 | + async function copy() { |
| 116 | + if (result?.ok) await navigator.clipboard.writeText(result.value); |
| 117 | + } |
| 118 | + |
| 119 | + return ( |
| 120 | + <div> |
| 121 | + <div className="mb-4 inline-flex rounded-lg border border-slate-300 p-1 dark:border-slate-700"> |
| 122 | + <button |
| 123 | + onClick={() => setDirection("csvToJson")} |
| 124 | + className={`rounded px-3 py-1 text-sm ${direction === "csvToJson" ? "bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900" : ""}`} |
| 125 | + > |
| 126 | + {t("direction.csvToJson")} |
| 127 | + </button> |
| 128 | + <button |
| 129 | + onClick={() => setDirection("jsonToCsv")} |
| 130 | + className={`rounded px-3 py-1 text-sm ${direction === "jsonToCsv" ? "bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900" : ""}`} |
| 131 | + > |
| 132 | + {t("direction.jsonToCsv")} |
| 133 | + </button> |
| 134 | + </div> |
| 135 | + |
| 136 | + <div className="grid gap-3 sm:grid-cols-[auto_auto_1fr]"> |
| 137 | + <label className="block"> |
| 138 | + <span className="text-sm font-medium">{t("input.delimiter")}</span> |
| 139 | + <select |
| 140 | + value={delimiter} |
| 141 | + onChange={(e) => setDelimiter(e.target.value)} |
| 142 | + className="mt-1 rounded border border-slate-300 px-2 py-1 text-sm dark:border-slate-700 dark:bg-slate-900" |
| 143 | + > |
| 144 | + <option value=",">{t("delim.comma")}</option> |
| 145 | + <option value=";">{t("delim.semicolon")}</option> |
| 146 | + <option value={"\t"}>{t("delim.tab")}</option> |
| 147 | + <option value="|">{t("delim.pipe")}</option> |
| 148 | + </select> |
| 149 | + </label> |
| 150 | + {direction === "csvToJson" && ( |
| 151 | + <label className="flex items-end gap-2 text-sm"> |
| 152 | + <input type="checkbox" checked={headerRow} onChange={(e) => setHeaderRow(e.target.checked)} className="size-4" /> |
| 153 | + <span>{t("input.headerRow")}</span> |
| 154 | + </label> |
| 155 | + )} |
| 156 | + </div> |
| 157 | + |
| 158 | + <label className="mt-4 block"> |
| 159 | + <span className="text-sm font-medium">{direction === "csvToJson" ? t("input.csv") : t("input.json")}</span> |
| 160 | + <textarea |
| 161 | + value={input} |
| 162 | + onChange={(e) => setInput(e.target.value)} |
| 163 | + rows={8} |
| 164 | + spellCheck={false} |
| 165 | + className="mt-1 w-full rounded border border-slate-300 px-3 py-2 font-mono text-sm dark:border-slate-700 dark:bg-slate-900" |
| 166 | + /> |
| 167 | + </label> |
| 168 | + |
| 169 | + <div className="mt-4"> |
| 170 | + <div className="flex items-center justify-between"> |
| 171 | + <span className="text-sm font-medium">{t("output")}</span> |
| 172 | + <button onClick={copy} disabled={!result?.ok} className="rounded border border-slate-300 px-3 py-1 text-xs hover:bg-slate-100 disabled:opacity-40 dark:border-slate-700 dark:hover:bg-slate-800"> |
| 173 | + {t("copy")} |
| 174 | + </button> |
| 175 | + </div> |
| 176 | + {!result ? ( |
| 177 | + <div className="mt-1 rounded border border-slate-200 bg-slate-50 p-3 text-sm text-slate-500 dark:border-slate-800 dark:bg-slate-900/50">{t("empty")}</div> |
| 178 | + ) : !result.ok ? ( |
| 179 | + <div className="mt-1 rounded border border-rose-300 bg-rose-50 p-3 text-sm text-rose-900 dark:border-rose-900 dark:bg-rose-900/20 dark:text-rose-200"> |
| 180 | + {t("error.label")}: {result.error} |
| 181 | + </div> |
| 182 | + ) : ( |
| 183 | + <pre className="mt-1 overflow-auto whitespace-pre rounded border border-slate-200 bg-slate-50 p-3 font-mono text-sm dark:border-slate-800 dark:bg-slate-900/50">{result.value}</pre> |
| 184 | + )} |
| 185 | + </div> |
| 186 | + </div> |
| 187 | + ); |
| 188 | +} |
0 commit comments