JSON(JavaScript Object Notation)は、データの交換に広く使われる軽量なテキストフォーマットです。JavaScriptではJSON.stringify()でオブジェクトをJSON文字列に変換し、JSON.parse()でJSON文字列をオブジェクトに変換します。API通信やデータの保存で必須の知識です。
基本的な使い方
JSON.stringify()はJavaScriptの値をJSON文字列に変換し、JSON.parse()はJSON文字列をJavaScriptの値に復元します。
JavaScript
// オブジェクトをJSON文字列に変換
const user = { name: "田中", age: 28, active: true };
const jsonStr = JSON.stringify(user);
console.log(jsonStr);
console.log(typeof jsonStr);
// JSON文字列をオブジェクトに変換
const parsed = JSON.parse(jsonStr);
console.log(parsed);
console.log(parsed.name);
// 配列も変換可能
const items = [1, "テキスト", true, null];
console.log(JSON.stringify(items));実行結果
{"name":"田中","age":28,"active":true}
string
{ name: "田中", age: 28, active: true }
田中
[1,"テキスト",true,null]JSON.stringify()の結果は純粋な文字列です。ネットワーク通信やlocalStorageへの保存時にはJSON文字列を使い、プログラム内で操作する際にはJSON.parse()でオブジェクトに戻します。
フォーマットとフィルタリング
JSON.stringify()にはオプション引数があり、整形出力やプロパティのフィルタリングが可能です。
JavaScript
const data = {
name: "田中",
age: 28,
password: "secret123",
department: "開発部"
};
// インデントを付けて整形(2スペース)
console.log(JSON.stringify(data, null, 2));
// 特定のキーだけを出力
console.log(JSON.stringify(data, ["name", "department"], 2));
// replacer関数でフィルタリング
const safe = JSON.stringify(data, (key, value) => {
if (key === "password") return undefined; // 除外
return value;
}, 2);
console.log(safe);実行結果
{
"name": "田中",
"age": 28,
"password": "secret123",
"department": "開発部"
}
{
"name": "田中",
"department": "開発部"
}
{
"name": "田中",
"age": 28,
"department": "開発部"
}実践的な活用例
JSONはAPI通信、localStorageへのデータ保存、深いコピーの作成など多くの場面で使われます。
JavaScript
// localStorageへの保存と読み出し
const settings = { theme: "dark", fontSize: 16, lang: "ja" };
// localStorage.setItem("settings", JSON.stringify(settings));
// const loaded = JSON.parse(localStorage.getItem("settings"));
// 深いコピー(簡易版)
const original = {
name: "田中",
scores: [80, 90, 85],
address: { city: "東京", ward: "渋谷区" }
};
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.scores.push(95);
deepCopy.address.city = "大阪";
console.log("元:", original.scores, original.address.city);
console.log("コピー:", deepCopy.scores, deepCopy.address.city);
// JSONの安全なパース
function safeParse(jsonStr, fallback = null) {
try {
return JSON.parse(jsonStr);
} catch (e) {
console.error("JSONパースエラー:", e.message);
return fallback;
}
}
console.log(safeParse('{"valid": true}'));
console.log(safeParse("invalid json", {}));実行結果
元: [80, 90, 85] 東京
コピー: [80, 90, 85, 95] 大阪
{ valid: true }
JSONパースエラー: Unexpected token...
{}JSONで扱えない値
undefined、function、SymbolはJSON.stringify()で自動的に除外されます。NaNとInfinityはnullに変換されます。Dateオブジェクトは文字列に変換されますが、JSON.parse()では文字列のまま復元されます。
深いコピーの注意点
JSON.parse(JSON.stringify())による深いコピーは、Date、RegExp、Map、Set、関数などを正しくコピーできません。これらを含むオブジェクトのコピーにはstructuredClone()を使用してください。循環参照がある場合もエラーになります。
まとめ
JSON.stringify()でJavaScriptの値をJSON文字列に変換JSON.parse()でJSON文字列をJavaScriptの値に復元- 第2・第3引数で整形出力やフィルタリングが可能
- API通信やlocalStorageで必須の機能
- 深いコピーには
structuredClone()の方が安全