// JSONデータを整形する
const data = {
name: "田中太郎",
age: 30,
skills: ["JavaScript", "Node.js"]
};
// 整形(インデント2空白)
const formatted = JSON.stringify(data, null, 2);
// 圧縮(1行に)
const minified = JSON.stringify(data);
const fs = require('fs');
// JSONファイルを読み込む
const data = fs.readFileSync('data.json');
const obj = JSON.parse(data);
// 整形して保存
fs.writeFileSync(
'formatted.json',
JSON.stringify(obj, null, 2)
);
const data = {
id: 1,
createdAt: new Date(),
items: [1, 2, 3]
};
// カスタム変換関数
const replacer = (key, value) => {
if (key === 'createdAt') {
return new Date(value).toISOString();
}
return value;
};
const formatted = JSON.stringify(data, replacer, 2);
try {
const invalidJson = '{"name": "John", age: 30}';
const obj = JSON.parse(invalidJson);
} catch (e) {
console.error('JSONパースエラー:', e.message);
// エラー位置を特定
const position = e.message.match(/position (\d+)/);
if (position) {
console.log(`エラー位置: ${position[1]}`);
}
}