js
JSON.stringify(value, replacer?, space?)القيم اللي مش ليها تمثيل في JSON بتتجاهل: undefined والدوال بتختفي من الـobjects وبتتحوّل لـnull في الـarrays. argument الـspace بتنسّق الناتج للقراءة.
حالات حدّية
- object فيها مرجع دائري (circular) بترمي TypeError: Converting circular structure to JSON.
- Date بتتحوّل لنص ISO تلقائيًا، وعند القراءة بترجع نصًا مش Date.
البرهان
js
const user = { name: 'سارة', age: 28, pass: undefined, tags: ['برمجة'] };
console.log(JSON.stringify(user));
console.log(JSON.stringify(user, null, 2));
console.log(JSON.stringify([undefined, () => 1, null]));
const a = {};
a.self = a;
try {
JSON.stringify(a);
} catch (e) {
console.log(e.constructor.name);
}النتيجة
{"name":"سارة","age":28,"tags":["برمجة"]}
{
"name": "سارة",
"age": 28,
"tags": [
"برمجة"
]
}
[null,null,null]
TypeError