JavaScriptでJSONをフォーマットする方法:完全ガイド
JavaScriptでJSONをフォーマット、文字列化、美化するすべての方法を学びましょう。基本的なJSON.stringify()から高度なフォーマット技法まで。
クイック回答: JSON.stringify() でのフォーマット
JavaScriptでJSONをフォーマットする最も速い方法は、インデント用のspaceパラメータと一緒にJSON.stringify()
を使用することです:
// Basic JSON formatting
const data = { name: "John", age: 30, city: "New York" };
const formatted = JSON.stringify(data, null, 2);
console.log(formatted);
// Output:
{
"name": "John",
"age": 30,
"city": "New York"
}
JSON.stringify() パラメータの理解
JSON.stringify()
はJSONフォーマットを完全に制御できる3つのパラメータを受け入れます:
構文
JSON.stringify(value, replacer, space)
- value: 変換するJavaScriptオブジェクト
- replacer: プロパティをフィルター/変換する関数または配列
- space: インデント用のスペース数または文字列
1. インデントでの基本フォーマット
const user = {
id: 1,
name: "Alice",
email: "alice@example.com",
preferences: {
theme: "dark",
notifications: true
}
};
// 2 spaces indentation (most common)
const formatted2 = JSON.stringify(user, null, 2);
// 4 spaces indentation
const formatted4 = JSON.stringify(user, null, 4);
// Tab indentation
const formattedTab = JSON.stringify(user, null, '\t');
2. リプレーサー関数でのカスタムフォーマット
フォーマット中にプロパティをフィルターまたは変換するためにリプレーサー関数を使用しましょう:
const userData = {
id: 123,
name: "Bob",
password: "secret123",
email: "bob@example.com",
lastLogin: new Date()
};
// Remove sensitive data and format dates
const safeReplacer = (key, value) => {
// Remove password field
if (key === 'password') return undefined;
// Format dates as ISO strings
if (value instanceof Date) return value.toISOString();
return value;
};
const formatted = JSON.stringify(userData, safeReplacer, 2);
console.log(formatted);
// Output:
{
"id": 123,
"name": "Bob",
"email": "bob@example.com",
"lastLogin": "2024-01-15T10:30:00.000Z"
}
3. 配列リプレーサーでのプロパティフィルター
const product = {
id: 456,
name: "Laptop",
price: 999.99,
inStock: true,
warehouse: "A1",
supplier: "TechCorp"
};
// Only include specific properties
const publicFields = ['id', 'name', 'price', 'inStock'];
const publicData = JSON.stringify(product, publicFields, 2);
// Output:
{
"id": 456,
"name": "Laptop",
"price": 999.99,
"inStock": true
}
高度なJSONフォーマット技法
カスタムJSONフォーマッター関数
アプリケーション全体で一貫したJSONフォーマットのために再利用可能な関数を作成しましょう:
function formatJSON(obj, options = {}) {
const {
indent = 2,
sortKeys = false,
removeEmpty = false,
dateFormat = 'iso'
} = options;
const replacer = (key, value) => {
// Remove null/undefined/empty values if requested
if (removeEmpty && (value === null || value === undefined || value === '')) {
return undefined;
}
// Format dates
if (value instanceof Date) {
return dateFormat === 'iso' ? value.toISOString() : value.toString();
}
return value;
};
let result = JSON.stringify(obj, replacer, indent);
// Sort keys if requested
if (sortKeys) {
const parsed = JSON.parse(result);
result = JSON.stringify(sortObjectKeys(parsed), null, indent);
}
return result;
}
function sortObjectKeys(obj) {
if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
return obj;
}
const sorted = {};
Object.keys(obj).sort().forEach(key => {
sorted[key] = sortObjectKeys(obj[key]);
});
return sorted;
}
// Usage
const data = { z: 1, a: 2, m: { b: 3, a: 4 } };
console.log(formatJSON(data, { sortKeys: true }));
エラーハンドリング付きJSONフォーマット
function safeJSONFormat(data, indent = 2) {
try {
// Handle circular references
const seen = new WeakSet();
const replacer = (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular Reference]';
}
seen.add(value);
}
return value;
};
return JSON.stringify(data, replacer, indent);
} catch (error) {
console.error('JSON formatting error:', error.message);
return `Error: ${error.message}`;
}
}
// Test with circular reference
const obj = { name: "Test" };
obj.self = obj; // Creates circular reference
console.log(safeJSONFormat(obj)); // Won't throw error
一般的なJSONフォーマットパターン
APIレスポンスフォーマット
// Format API response for debugging
function debugAPI(response) {
console.log('API Response:');
console.log(JSON.stringify(response, null, 2));
}
// Format for logging with timestamp
function logJSON(data, label = '') {
const timestamp = new Date().toISOString();
console.log(`[${timestamp}] ${label}`);
console.log(JSON.stringify(data, null, 2));
}
// Pretty print in development, minify in production
function formatForEnvironment(data) {
return process.env.NODE_ENV === 'development'
? JSON.stringify(data, null, 2)
: JSON.stringify(data);
}
設定ファイル生成
function generateConfig(options) {
const config = {
version: "1.0.0",
environment: options.env || "development",
database: {
host: options.dbHost || "localhost",
port: options.dbPort || 5432,
name: options.dbName
},
features: {
authentication: true,
logging: options.env !== "production",
caching: options.env === "production"
}
};
// Format with comments (for .json files that support them)
return JSON.stringify(config, null, 2);
}
const devConfig = generateConfig({
env: "development",
dbHost: "localhost",
dbName: "myapp_dev"
});
console.log(devConfig);
JSONフォーマットのベストプラクティス
一貫したインデントの使用
プロジェクト全体で一貫して2スペースまたは4スペースを使用。ほとんどのJavaScriptプロジェクトで2スペースを使用します。
循環参照の処理
未知のデータ構造をフォーマットする際は必ず循環参照検出を実装してください。
対象に合わせたフォーマット
開発/デバッグ用には美しいフォーマット、本番/API用にはミニファイ化を使用しましょう。
機密データのフィルター
パスワード、トークン、その他の機密情報を除去するためにリプレーサー関数を使用しましょう。
よくある落とし穴と解決策
循環参照エラー
問題: TypeError: Converting circular structure to JSON
解決策: WeakSetを使用して訪問済みオブジェクトを追跡し、循環を検出します。
日付シリアライゼーションの問題
問題: 日付が文字列になりDate型を失う
解決策: リプレーサー関数を使用して日付を一貫してフォーマットするか、型ヒントを含めます。
大きなオブジェクトでのパフォーマンス
ヒント: JSON.stringify()は非常に大きなオブジェクトでは遅くなる可能性があります
解決策: 大きなデータセットにはストリーミングJSONパーサーを使用するか、ページネーションを実装します。
JSONフォーマットのテスト
// Unit test example for JSON formatting
function testJSONFormatting() {
const testData = {
string: "test",
number: 42,
boolean: true,
array: [1, 2, 3],
object: { nested: "value" }
};
// Test basic formatting
const formatted = JSON.stringify(testData, null, 2);
console.assert(formatted.includes(' "string"'), 'Should have 2-space indentation');
// Test property filtering
const filtered = JSON.stringify(testData, ['string', 'number'], 2);
console.assert(!filtered.includes('boolean'), 'Should filter out non-listed properties');
// Test circular reference handling
testData.self = testData;
try {
JSON.stringify(testData);
console.error('Should have thrown circular reference error');
} catch (e) {
console.log('✓ Circular reference correctly detected');
}
}
testJSONFormatting();
まとめ
JavaScriptでのJSONフォーマットはJSON.stringify()
で簡単ですが、リプレーサーとspaceパラメータをマスターすることで出力を強力に制御できます。循環参照や機密データなどのエッジケースを処理し、用途に合ったフォーマットスタイルを選択することを忘れないでください—開発用には美しいフォーマット、本番用にはミニファイ化。
重要ポイント:
- 基本的な美しいフォーマットには
JSON.stringify(obj, null, 2)
を使用 - データフィルターと変換のためにリプレーサー関数を実装
- ランタイムエラーを避けるために循環参照を処理
- プロジェクト全体で一貫してインデントスタイルを選択
- エッジケースでフォーマット関数をテスト