紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS JSON.stringify 用法:物件轉 JSON 字串、replacer 與縮排

JS JSON.stringify 用法:物件轉 JSON 字串、replacer 與縮排 特色圖片

JSON.stringify() 是 JavaScript 把值轉成 JSON 字串的靜態方法,常用在把物件存進 localStorage、或把資料送給伺服器之前。

白話一點,它就像把物件拍成一張文字快照;之後可以用 JSON.parse() 還原。

語法

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
參數說明
value要轉成 JSON 字串的值
replacer(選用)函式,或由字串、數字組成的陣列,用來轉換值或指定要輸出的屬性
space(選用)數字或字串,用來縮排,讓輸出比較好讀

回傳 JSON 字串,或是 undefined。轉換過程中遇到循環參照或 BigInt 值,會丟出 TypeError。

基本用法

console.log(JSON.stringify({}));                 // {}
console.log(JSON.stringify(true));               // true
console.log(JSON.stringify('foo'));              // "foo"
console.log(JSON.stringify([1, 'false', false])); // [1,"false",false]
console.log(JSON.stringify({ x: 5, y: 6 }));     // {"x":5,"y":6}

字串轉出來會帶雙引號,因為結果本身就是合法的 JSON 文字。

哪些值會被省略或改變

MDN 列出的轉換規則,整理成表:

輸入在物件中在陣列中
undefined、函式、Symbol屬性被省略變成 null
NaN、Infinity變成 null變成 null
Symbol 當屬性名稱完全忽略—
Date呼叫 toJSON(),輸出 ISO 格式字串同左
Map、Set變成 {}變成 {}
console.log(JSON.stringify([NaN, null, Infinity]));
// [null,null,null]

console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol('')] }));
// {"x":[10,null,null,null]}

console.log(JSON.stringify({ x: undefined, y: Object, z: Symbol('') }));
// {}

console.log(JSON.stringify({ [Symbol('foo')]: 'foo', k: 1 }));
// {"k":1}

console.log(JSON.stringify(new Date(Date.UTC(2006, 0, 2, 15, 4, 5))));
// "2006-01-02T15:04:05.000Z"

console.log(JSON.stringify([new Set([1]), new Map([[1, 2]])]));
// [{},{}]

直接傳入 undefined 或函式這類「純」值,回傳值是 undefined,不是字串:

console.log(JSON.stringify(undefined)); // undefined
console.log(JSON.stringify(() => {}));  // undefined

另外,MDN 說明陣列只會序列化索引 0 到 length - 1 的元素,其他屬性會被忽略:

const a = ['foo', 'bar'];
a.baz = 'quux';
console.log(JSON.stringify(a)); // ["foo","bar"]

replacer 參數

replacer 是函式

函式會收到 key 與 value,this 是包含這個鍵的物件。回傳值會取代原本的值:

  • 回傳數字、字串、布林值或 null:直接當成屬性值輸出。
  • 回傳函式、Symbol 或 undefined:屬性不會出現在輸出中。
  • 回傳其他物件:遞迴處理它的每個屬性。

初始物件本身也會呼叫一次,此時 key 是空字串。下面的例子濾掉所有字串值:

const foo = {
  foundation: 'Mozilla',
  model: 'box',
  week: 45,
  transport: 'car',
  month: 7
};

console.log(JSON.stringify(foo, (key, value) =>
  typeof value === 'string' ? undefined : value
));
// {"week":45,"month":7}

replacer 是陣列

陣列的內容是要輸出的屬性名稱,只有字串與數字有效:

console.log(JSON.stringify(foo, ['week', 'month']));
// {"week":45,"month":7}

用 replacer 序列化 Map

Map 預設會變成 {},可以用 replacer 轉成想要的格式:

console.log(JSON.stringify(
  { s: new Map([['a', 1]]) },
  (key, value) => (value instanceof Map ? Object.fromEntries(value) : value)
));
// {"s":{"a":1}}

space 參數:縮排輸出

space 是數字時,代表每一層縮排幾個空白;是字串時,用該字串縮排。MDN 說明縮排最多 10:數字超過 10 當成 10,字串只取前 10 個字元。

console.log(JSON.stringify({ uno: 1, dos: 2 }, null, 2));
/*
{
  "uno": 1,
  "dos": 2
}
*/

console.log(JSON.stringify({ uno: 1, dos: 2 }, null, '\t'));
/*
{
	"uno": 1,
	"dos": 2
}
*/

第二個參數不需要 replacer 時,傳 null 即可。

toJSON():自訂序列化結果

物件如果有 toJSON() 方法,序列化時會改用它的回傳值。toJSON() 會收到一個引數 key:

  • 物件是某個屬性的值:屬性名稱。
  • 物件在陣列裡:索引(字串)。
  • 直接對這個物件呼叫 JSON.stringify():空字串。
const obj = {
  data: 'data',
  toJSON(key) {
    return key ? `Now I am a nested object under key '${key}'` : this;
  }
};

console.log(JSON.stringify(obj));      // {"data":"data"}
console.log(JSON.stringify({ obj }));  // {"obj":"Now I am a nested object under key 'obj'"}
console.log(JSON.stringify([obj]));    // ["Now I am a nested object under key '0'"]

console.log(JSON.stringify({
  x: 5,
  y: 6,
  toJSON() { return this.x + this.y; }
}));
// 11

Date 就是靠內建的 toJSON()(回傳值與 toISOString() 相同)轉成字串的。

會丟 TypeError 的情況

循環參照(物件的屬性又指回自己)與 BigInt 值都無法序列化:

const c = {};
c.myself = c;

try {
  JSON.stringify(c);
} catch (e) {
  console.log(e.name); // TypeError
}

try {
  JSON.stringify({ x: 2n });
} catch (e) {
  console.log(e.name); // TypeError
}

BigInt 的做法,MDN 說明可以替 BigInt.prototype.toJSON 提供轉換(例如轉成字串),或在 replacer 裡處理,讓序列化行為由你明確決定。

用 JSON 複製物件要注意

JSON.parse(JSON.stringify(obj)) 常被用來複製物件,但它會經過上面所有轉換規則:Date 會變成字串,undefined 與函式會消失:

const src = { n: 1, d: { x: [1, 2] }, t: new Date(0) };

const cp = JSON.parse(JSON.stringify(src));
console.log(cp.t);          // 1970-01-01T00:00:00.000Z
console.log(typeof cp.t);   // string

console.log(structuredClone(src).t instanceof Date); // true

MDN 建議,要深層複製時可以改用 structuredClone(),它也支援循環參照。

補充說明:範例輸出為 Node.js v22.20.0 的執行結果。

搭配 localStorage 儲存物件

localStorage 只能存字串,存物件前要先 JSON.stringify(),讀回來再 JSON.parse()。完整說明可看站內文章:

參考資料與延伸閱讀

發佈留言