コンテンツへスキップ
uencoder

CSV を JSON に変換する方法

CSV の表形式データを、プログラムからのアクセスと API での利用のために JSON オブジェクトに変換します。

问题

CSV 形式のデータを、JavaScript や API で処理するために JSON にする必要があります。

前提条件

  • CSV 形式の理解
  • JSON の配列とオブジェクトの理解

ステップ

  1. 1. Parse the CSV header and rows

    Read the first line as the header row to get field names. Read each subsequent line as a data row, splitting on the delimiter (comma by default). Handle quoted fields that contain commas or newlines by respecting CSV quoting rules.

    入力
    name,age,city\nAlice,30,NYC
    输出
    headers: [name, age, city]
  2. 2. Map rows to JSON objects

    For each data row, create a JSON object where each header field is a key and the corresponding cell is the value. Decide whether to infer types (numbers, booleans) or keep all values as strings. Type inference is convenient but can misinterpret values like zip codes.

    入力
    Alice,30,NYC
    输出
    {"name":"Alice","age":30,"city":"NYC"}
  3. 3. Assemble and output the JSON array

    Collect all row objects into a JSON array. Format the output with indentation for readability if needed. Validate that the number of fields in each row matches the header count.

    入力
    [{Alice},{Bob}]
    输出
    JSON array of objects

期待される結果

CSV の各行を、ヘッダーから派生したキーを持つオブジェクトとして表した JSON 配列。

よくあるエラー

Comma inside a quoted field splits incorrectly
Use a proper CSV parser that respects quoting rules. Do not split on commas with a simple string split.
Zip codes or IDs lose leading zeros
If you infer types, numeric conversion strips leading zeros. Keep such fields as strings or use a schema to specify types.

トラブルシューティング指引

  • If rows have inconsistent field counts, check for unquoted commas or multiline fields in the CSV.
  • For large CSV files, use a streaming parser to avoid loading everything into memory.

セキュリティ上の制限

  • CSV injection (formula injection) can affect spreadsheet applications. Sanitize cells that start with =, +, -, or @ if the output will be opened in a spreadsheet.

関連ツール

参考链接