核心 API
JSON.stringify(value[, replacer[, space]])
value:要序列化的值
replacer:函數或數組,過濾/轉換屬性
space:縮進控制—— 數字(空格數) 或 字符串(縮進字符),最多 10 位
縮進參數用法
var obj = { a: 1, b: { c: 2, d: [3, 4] } };
// 1. 縮進 4 個空格
console.log(JSON.stringify(obj, null, 4));
/* 輸出:
{
"a": 1,
"b": {
"c": 2,
"d": [
3,
4
]
}
}
*/
// 2. 縮進 1 個 Tab (\t)
console.log(JSON.stringify(obj, null, '\t'));
/* 輸出:
{
"a": 1,
"b": {
"c": 2,
"d": [
3,
4
]
}
}
*/
// 3. 自定義縮進字符串(如 "··")
console.log(JSON.stringify(obj, null, '··'));
/* 輸出:
{
··"a": 1,
··"b": {
····"c": 2,
····"d": [
······3,
······4
····]
··}
}
*/
replacer 進階用法
函數過濾/轉換
var data = {
id: 1,
password: 'secret',
createdAt: new Date('2024-01-01'),
nested: { token: 'abc' }
};
// 過濾掉敏感字段,日期格式化
var json = JSON.stringify(data, function(key, value) {
if (key === 'password' || key === 'token') return undefined; // 排除
if (value instanceof Date) return value.toISOString(); // 轉換
return value;
}, 2);
console.log(json);
/* 輸出:
{
"id": 1,
"createdAt": "2024-01-01T00:00:00.000Z",
"nested": {}
}
*/
數組白名單
// 只保留 id 和 createdAt
JSON.stringify(data, ['id', 'createdAt'], 2);
toJSON() 自定義序列化
var user = {
name: 'Alice',
password: '123456',
toJSON: function() {
// 返回要序列化的純對象
return { name: this.name }; // 自動排除 password
}
};
console.log(JSON.stringify(user, null, 2));
// { "name": "Alice" }
常見坑與解決
| 問題 | 原因 | 解決 |
循環引用報錯 Converting circular structure to JSON | 對象直接/間接引用自身 | 用 flatted 庫或自定義 replacer 記錄已見對象 |
undefined/函數/Symbol 丟失 | JSON 標準不支持 | replacer 中手動轉換:typeof v === 'function' ? v.toString() : v |
| BigInt 序列化失敗 | ES2020 新類型,JSON 不支持 | replacer 中 typeof v === 'bigint' ? v.toString() + 'n' : v |
| 大數字精度丟失 | JS Number 雙精度限制 | 傳輸前轉字符串,或用 json-bigint 庫 |
Node.js 寫入格式化 JSON 文件
const fs = require('fs');
const config = { port: 3000, db: { host: 'localhost', port: 5432 } };
// 同步寫入(小文件)
fs.writeFileSync('config.json', JSON.stringify(config, null, 2), 'utf8');
// 異步寫入(大文件/生產環境)
fs.promises.writeFile('config.json', JSON.stringify(config, null, 2))
.then(() => console.log('寫入成功'))
.catch(err => console.error('寫入失敗:', err));
在線工具替代
開發調試階段,推薦使用瀏覽器 DevTools Console 直接輸入 copy(JSON.stringify(obj, null, 2)) 創建到剪貼板,或使用 JSON Formatter 等在線工具。
copyright ©
萬盛學電腦網 all rights reserved