CSV 轉 JSON、JSON 轉 CSV 線上轉換器:保留 0 開頭編號

先選轉換方向再貼上資料。CSV 轉 JSON 以第一列當欄位名稱,輸出物件陣列;JSON 轉 CSV 接受物件陣列或陣列的陣列,巢狀資料寫成 JSON 文字。可複製或下載 .json、.csv,0 開頭的編號預設保留為文字,資料不會上傳。

所屬專區:AI 與效率。版本 1.0.0,最後測試於。

適合誰:員工識別證小編記者證

轉換方向
欄位值

轉換時,0912 這類開頭為 0 的值、位數太多會失真的長編號、1.50 這類寫法會保留為文字,避免資料被改掉。

JSON

在左側貼上資料,這裡會即時顯示轉換結果。

內容只在你的瀏覽器處理,不會送出。

適合什麼時候用

  • 把試算表匯出的 CSV 轉成 JSON,給網頁、程式或自動化流程使用
  • 把 API 或 AI 產生的 JSON 轉成 CSV,用 Excel 或 Google 試算表檢查
  • 找出 CSV 中引號沒關好、欄位名稱重複或空白等格式問題

怎麼使用

  1. 選擇「CSV → JSON」或「JSON → CSV」。
  2. 貼上資料,或按「填入範例」。
  3. CSV → JSON 時確認分隔符號(預設自動偵測)、是否轉換數字,以及要縮排排版或壓成一行。
  4. 右側即時顯示結果;格式有錯時會顯示原因與位置。按「複製」或「下載」取得結果。

範例:CSV 轉 JSON

商品編號,品名,數量,含稅
00123,"筆記本, A5",3,true
00456,原子筆,,false

選「轉換數字、true/false、空白→null」並勾選縮排後,得到:

[
  {
    "商品編號": "00123",
    "品名": "筆記本, A5",
    "數量": 3,
    "含稅": true
  },
  {
    "商品編號": "00456",
    "品名": "原子筆",
    "數量": null,
    "含稅": false
  }
]
  • 00123 開頭是 0,保留為文字。
  • "筆記本, A5" 用雙引號包住,裡面的逗號不會被當成分隔符號。
  • 第二筆的數量是空白,轉成 null;若選「全部保留為文字」則是 ""。

欄位值轉換規則

原始內容 全部保留為文字 轉換數字、true/false、空白→null
3 "3" 3
-3.5 "-3.5" -3.5
0912345678 "0912345678" "0912345678"
1.50 "1.50" "1.50"(轉成數字會變 1.5)
12345678901234567890 文字 文字(轉成數字會失真)
TRUE、false 文字 true、false
空白 "" null

JSON 轉 CSV 的規則

  • 物件陣列:所有物件出現過的鍵都會成為欄位,順序依第一次出現的位置;某筆缺少的欄位留空。
  • 陣列的陣列:每個內層陣列是一列,不另外加標題列。
  • 巢狀物件或陣列寫成 JSON 文字,例如 ["文具","紙類"];null 輸出為空白。

需要把結果貼到文件或 AI 對話時,可以再用 Markdown 表格產生器 轉成表格。請 AI 依固定欄位輸出 JSON 時,在 Prompt 的「輸出格式」列出欄位名稱,寫法見寫好 AI Prompt 的六個欄位。

限制與注意事項

  • 數字轉換採保守規則:只轉換「轉回文字後完全相同」的十進位數字,所以 0912、1.50、1e3、+5,以及位數太多、轉成數字會失真的長編號都保留為文字;日期也不會轉換。
  • JSON 轉 CSV 時,巢狀物件與陣列會以 JSON 文字放在同一格,不會展開成多個欄位。
  • 為了避免試算表把內容當成公式執行,以 =、+、-、@ 開頭的文字會在前面加上 ';如果 CSV 要給程式讀取,請留意這個前綴。數字型態的負數不受影響。
  • JSON 錯誤的行列位置取自瀏覽器的錯誤訊息,不同瀏覽器提供的資訊不同,有時只能顯示錯誤原因、沒有位置。
  • 超過約 5 MB 的資料仍在本機轉換,但可能讓瀏覽器變慢;結果很長時畫面只顯示開頭,完整內容請用複製或下載。
  • 空白行會被略過,欄位名稱前後的空白會被去除。

隱私與無障礙

貼上的資料只在你的瀏覽器轉換,不會上傳到任何伺服器;下載的檔案直接由瀏覽器產生,關閉分頁後不保留。

轉換方向與選項都是有標籤的單選、勾選或下拉選單;錯誤訊息會立即通知螢幕閱讀器並說明位置與修正方式;轉換筆數會以文字更新;可只用鍵盤完成貼上、轉換、複製與下載。

搭配 AI 使用的 Prompt 範本

把【】裡的內容換成你的情況再貼到 AI 工具。送出前請確認沒有個資或機密資料,並自行核對 AI 的回答。

(貼上前請刪除或遮蔽姓名、電話、Email、身分證號等個人資料;需要區分時用代號,例如 會員A。)
請幫我把下面的資料轉換格式並整理乾淨。

資料來源與用途:【例:從 Google 試算表匯出的報名表,要匯入網站】
原始資料:【貼上 CSV 或 JSON;資料很多時先貼前 20 列試轉】
要轉成:【JSON 物件陣列/CSV】
欄位要求:【例:欄位名稱改成英文小寫;電話保留開頭的 0;日期統一成 2026-11-21 的格式】

請輸出:
1. 資料問題清單(Markdown 表格):列號、欄位、問題(例如引號沒關好、欄位數不符、空白、重複列)、建議處理方式。
2. 轉換後的完整結果,放在程式碼區塊中。
3. 轉換前後的列數與欄位數,寫出算式說明差異(例如刪了幾列空白、合併了幾列重複)。

規則:不要補上或猜測原始資料沒有的值,空值保留為空並列進問題清單;無法判斷的值標成【需查證】,你採用的轉換規則(例如型態、日期格式)標成【假設】。0 開頭的電話與長編號一律保留為文字。
(拿到結果後,可把原始資料貼到本站 /tools/csv-json/ 再轉一次,核對列數與欄位是否一致。)

計算邏輯原始碼

工具的計算部分是以下 TypeScript 函式,沒有呼叫任何外部服務。你可以複製到自己的專案使用,授權為 MIT License(Copyright © 2026 Explore Hub;保留此著作權聲明即可自由使用、修改、商用)。

csv-json.ts
export type Delimiter = ',' | '\t' | ';';
export type Cell = string | number;

/** Above this many characters (about 5 MB of ASCII) the UI warns that converting may be slow. */
export const LARGE_INPUT = 5_000_000;

const stripBom = (s: string) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);

/**
 * Guess the delimiter from the first non-blank line, ignoring quoted text.
 * A tab wins outright (Excel / Google 試算表 copy cells as tab-separated); otherwise the more frequent of ; and , (tie → ,).
 */
export function detectDelimiter(text: string): Delimiter {
  const first = stripBom(text).split(/\r\n|\r|\n/).find((l) => l.trim() !== '') ?? '';
  const line = first.replace(/"(?:[^"]|"")*"/g, '');
  const count = (d: string) => line.split(d).length - 1;
  if (count('\t') > 0) return '\t';
  return count(';') > count(',') ? ';' : ',';
}

/**
 * RFC 4180 parser: fields wrapped in "…" may contain the delimiter, line breaks and "" (an escaped quote).
 * Accepts CRLF, LF or CR line endings and strips a leading UTF-8 BOM. Blank lines are skipped.
 * A quote only opens a quoted field at the start of a field; elsewhere it is ordinary text (5" 螢幕).
 * Throws with the line and character position of a quote that is never closed.
 */
export function parseCsv(text: string, delimiter: Delimiter = ','): string[][] {
  const s = stripBom(text);
  const rows: string[][] = [];
  let row: string[] = [];
  let field = '';
  let atFieldStart = true;
  let line = 1;
  let lineStart = 0;

  const endRow = () => {
    row.push(field);
    if (!(row.length === 1 && row[0] === '')) rows.push(row);
    row = [];
    field = '';
    atFieldStart = true;
  };

  for (let i = 0; i < s.length; i++) {
    const c = s[i];
    if (atFieldStart && c === '"') {
      const openLine = line;
      const openCol = i - lineStart + 1;
      for (i++; ; i++) {
        if (i >= s.length) {
          throw new Error(`第 ${openLine} 行第 ${openCol} 個字元的引號 " 沒有結束:請補上結尾的 ",或把欄位內的 " 寫成 ""。`);
        }
        if (s[i] === '"') {
          if (s[i + 1] !== '"') break; // closing quote; the loop's i++ moves past it
          field += '"';
          i++;
        } else {
          if (s[i] === '\n') {
            line++;
            lineStart = i + 1;
          }
          field += s[i];
        }
      }
      atFieldStart = false;
    } else if (c === delimiter) {
      row.push(field);
      field = '';
      atFieldStart = true;
    } else if (c === '\n' || c === '\r') {
      if (c === '\r' && s[i + 1] === '\n') i++;
      endRow();
      line++;
      lineStart = i + 1;
    } else {
      field += c;
      atFieldStart = false;
    }
  }
  if (field !== '' || row.length > 0 || !atFieldStart) endRow();
  return rows;
}

/** Empty headers become 欄位_<column number>; repeats get _2, _3 … so every key is unique and the result is deterministic. */
export function uniqueHeaders(raw: readonly string[]): string[] {
  const used = new Set<string>();
  return raw.map((h, i) => {
    const base = h.trim() || `欄位_${i + 1}`;
    let name = base;
    for (let n = 2; used.has(name); n++) name = `${base}_${n}`;
    used.add(name);
    return name;
  });
}

/**
 * Optional type conversion: "" → null, true/false (any case) → boolean, plain decimal numbers → number.
 * A number is converted only if writing it back gives the exact same text, so 0912 (leading zero),
 * 12345678901234567890 (beyond double precision), 1.50, +5 and 1e3 all stay strings.
 */
export function convertValue(s: string): string | number | boolean | null {
  if (s === '') return null;
  if (/^true$/i.test(s)) return true;
  if (/^false$/i.test(s)) return false;
  if (/^-?\d+(\.\d+)?$/.test(s) && String(Number(s)) === s) return Number(s);
  return s;
}

export interface CsvToJsonOptions {
  delimiter: Delimiter;
  /** false: every value stays a string. */
  convertTypes: boolean;
  pretty: boolean;
}

/** First row = keys. Rows shorter than the header get "" (or null); extra cells get their own 欄位_N key. */
export function csvToJson(text: string, { delimiter, convertTypes, pretty }: CsvToJsonOptions) {
  const rows = parseCsv(text, delimiter);
  if (rows.length === 0) throw new Error('沒有資料:請貼上 CSV,第一列放欄位名稱。');
  const width = rows.reduce((w, r) => Math.max(w, r.length), 0);
  const keys = uniqueHeaders(Array.from({ length: width }, (_, i) => rows[0][i] ?? ''));
  // Object.fromEntries defines own properties, so a header named "__proto__" is kept as data.
  const data = rows.slice(1).map((r) => Object.fromEntries(keys.map((k, i) => [k, convertTypes ? convertValue(r[i] ?? '') : (r[i] ?? '')])));
  return { json: JSON.stringify(data, null, pretty ? 2 : undefined), records: data.length, keys };
}

/** JSON.parse with a Chinese message and an approximate line/column taken from the engine's error text when it has one. */
export function parseJson(text: string): unknown {
  const s = stripBom(text);
  if (s.trim() === '') throw new Error('沒有資料:請貼上 JSON 陣列,例如 [{"名稱":"A"}]。');
  try {
    return JSON.parse(s);
  } catch (e) {
    const msg = (e as Error).message;
    const at = (index: number) => {
      const before = s.slice(0, index).split('\n');
      return `(約第 ${before.length} 行第 ${before[before.length - 1].length + 1} 個字元)`;
    };
    // Engines differ: "line 3 column 5" (Firefox, newer V8), "position 12" (V8), or nothing (Safari).
    const lc = /line (\d+) column (\d+)/.exec(msg);
    const pos = /position (\d+)/.exec(msg);
    // V8 gives no position for a trailing comma in an array ("[1,]"), so look for one ourselves.
    const comma = /Unexpected token '[\]}]'/.test(msg) ? /,\s*[\]}]/.exec(s) : null;
    const where = lc ? `(約第 ${lc[1]} 行第 ${lc[2]} 個字元)` : pos ? at(Number(pos[1])) : comma ? at(comma.index) : '';
    throw new Error(`JSON 格式錯誤${where}:${msg}。常見原因:最後一項後多了逗號、用了單引號、鍵名沒加雙引號。`);
  }
}

const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);

/** Numbers stay numbers; null → empty; nested objects/arrays are written as JSON text inside the cell. */
const toCell = (v: unknown): Cell =>
  v === null || v === undefined ? '' : typeof v === 'number' ? v : typeof v === 'string' ? v : typeof v === 'boolean' ? String(v) : JSON.stringify(v);

/**
 * Array of objects → header row (union of keys, in order of first appearance) + one row per object.
 * Array of arrays → rows as they are, no header. A single object is treated as a one-item array.
 * Pass the result to toCsv / downloadCsv (csv.ts), which quote cells and neutralise spreadsheet formulas.
 */
export function jsonToRows(data: unknown): Cell[][] {
  const list = Array.isArray(data) ? data : isRecord(data) ? [data] : null;
  if (!list) throw new Error('JSON 最外層需要是陣列 [ … ](或單一物件 { … })。');
  if (list.length === 0) throw new Error('陣列是空的,沒有資料可以轉換。');

  if (Array.isArray(list[0])) {
    return list.map((r, i) => {
      if (!Array.isArray(r)) throw new Error(`第 ${i + 1} 筆不是陣列:陣列裡要全部是陣列,或全部是物件。`);
      return r.map(toCell);
    });
  }
  const keys = new Set<string>();
  list.forEach((r, i) => {
    if (!isRecord(r)) throw new Error(`第 ${i + 1} 筆不是物件:陣列裡要全部是物件 { … },或全部是陣列 [ … ]。`);
    for (const k of Object.keys(r)) keys.add(k);
  });
  const header = [...keys];
  return [header, ...list.map((r) => header.map((k) => toCell(r[k])))];
}

常見問題

為什麼 0912345678 沒有變成數字?

轉成數字會失去開頭的 0,電話、郵遞區號、商品編號就會被改掉。即使選了「轉換數字」,工具也只轉換轉回文字後完全相同的數字;選「全部保留為文字」則所有值都維持字串。

欄位名稱重複或空白會怎樣?

空白的欄名改成「欄位_欄號」,例如第 2 欄沒有名稱就叫「欄位_2」;重複的名稱依序加上 _2、_3。規則固定,同一份資料每次轉換的結果都一樣。

出現「引號沒有結束」怎麼辦?

訊息會指出是第幾行第幾個字元開始的引號。欄位內要放雙引號時要寫成兩個 "",整個欄位再用一對雙引號包起來;若引號只是內容的一部分且不在欄位開頭,可以不用處理。

下載的 CSV 和 JSON 有什麼差別?

CSV 檔以 UTF-8 編碼並在開頭加上 BOM 標記,目的是讓 Excel 正確顯示中文;JSON 檔是一般 UTF-8 文字,不加 BOM,方便程式直接讀取。

相關內容

  • Markdown 表格產生器工具

    免費 Markdown 表格產生器。從 Excel、Google 試算表複製儲存格或貼上 CSV,自動判斷分隔符號,處理儲存格內換行與直線符號,可設定每欄對齊與欄寬對齊,即時預覽並複製。

  • AI Prompt 產生器工具

    免費 AI Prompt 產生器。依角色、任務、背景、目標、限制、輸出格式六個欄位填空,即時組成結構清楚的 Prompt,可複製到 ChatGPT、Claude、Gemini,並提醒移除個資。

  • 提案架構產生器工具

    免費提案大綱工具。依提案名稱、對象、背景、問題、目標、做法、時程、預算、風險與成效指標填空,整理成 Markdown 大綱與里程碑表格,並產生請 AI 寫成提案初稿的 Prompt,缺的資訊標成【待補】。

  • 搜尋結果標題與描述預覽工具

    免費搜尋結果預覽工具。輸入頁面標題、meta description 與網址,查看桌機與手機的估計顯示、字數與可能被截斷的位置,並提醒重複關鍵字、描述過短等常見問題。

  • 自己做網頁小工具:從計算邏輯到可用、可及、不外洩資料

    用本站 MIT 授權的程式碼示範怎麼做網頁小工具:計算與畫面分開、用 node:test 測試、處理 type="number" 與 NaN、用 Intl.NumberFormat 格式化金額、無障礙檢查、資料不外洩,以及 CSV 公式注入的防法。

  • 寫好 AI Prompt 的六個欄位:角色、任務、背景、目標、限制、輸出格式

    把 Prompt 拆成角色、任務、背景、目標、限制、輸出格式六個欄位,附活動企劃、會議重點、家長通知的寫法對照、可複製範例,以及檢查 AI 輸出與保護資料的做法。