この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:2
更新日時:2026-06-10 12:08:57
タイトル: 配列からJSONに変換
本稿は JavaScript の配列を JSON 形式の文字列に変換する方法に関する記事です。サーバへの送信や localStorage への保存、ログ出力などで頻繁に必要になる操作です。
使用する関数
| 関数 |
|
JSON.stringify(value [, replacer [, space ]])
|
value には配列やオブジェクトを渡します。戻り値として JSON 文字列が返ります。
基本的な使い方
|
// 1. 単純配列
const arr = [1, 2, 3, 4];
const json = JSON.stringify(arr);
console.log(json); // "[1,2,3,4]"
// 2. オブジェクトを含む配列
const users = [
{ id: 1, name: "Taro" },
{ id: 2, name: "Jiro" }
];
console.log(JSON.stringify(users));
// "[{"id":1,"name":"Taro"},{"id":2,"name":"Jiro"}]"
// 3. 整形して読みやすく (4スペースインデント)
console.log(JSON.stringify(users, null, 4));
// 4. 一部キーのみ出力 (replacer)
console.log(JSON.stringify(users, ["id"]));
// "[{"id":1},{"id":2}]"
|
引数のオプション
| 引数 | 役割 |
value | 変換する値 (配列・オブジェクト・プリミティブ) |
replacer | キーをフィルタする関数または配列。不要なフィールドを除外可能 |
space | 整形時のインデント。数字 (1〜10) または文字列 ("\t"等) |
逆変換 (JSON → 配列・オブジェクト)
|
const json = '[1,2,3]';
const arr = JSON.parse(json);
console.log(arr[0]); // 1
|
JSON.stringify の挙動で注意したい型
| 入力 | 結果 |
undefined / 関数 | キーごと無視される (配列内では null に置換) |
NaN / Infinity | null に置換 |
Date | ISO8601 文字列に変換 ("2026-05-13T...") |
BigInt | 例外 (TypeError) |
| 循環参照 | 例外 (TypeError: Converting circular structure to JSON) |
Map / Set | 空オブジェクト {} になる (中身は出ない) |
toJSON() メソッドを持つオブジェクト | その戻り値が使われる |
用途別の応用
| 用途 | 例 |
| fetch 送信 | fetch(url, { method: "POST", body: JSON.stringify(arr), headers: {"Content-Type":"application/json"} }) |
| localStorage 保存 | localStorage.setItem("items", JSON.stringify(arr)) → 復元は JSON.parse |
| ディープコピー (簡易) | const copy = JSON.parse(JSON.stringify(obj)) (Date 等の特殊型は失われる) |
| ログ出力 | console.log(JSON.stringify(obj, null, 2)) で読みやすく |
注意点
- 循環参照があるとエラーになる。対象オブジェクトの構造を見直すか、
replacer でカット
- BigIntは変換不可。文字列化してから
JSON.stringify へ
- Date オブジェクトは ISO 文字列になるため、復元側で
new Date() が必要
- private な情報 (パスワードハッシュ等) を含めない。
replacer で除外する
- ディープコピー目的で使う場合、
structuredClone() や lodash.cloneDeep のほうが正確
関連
- 親カテゴリ: JSON
- JavaScript本体: JavaScript
- 関連: Fetch API、localStorage、IndexedDB