Code
// Parsen mit Fallback, entfernt __proto__/constructor (Schutz vor Prototype Pollution)
const safeParse = (text, fallback = null) => {
if (typeof text !== 'string') return fallback;
try {
return JSON.parse(text, (k, v) =>
k === '__proto__' || k === 'constructor' ? undefined : v);
} catch {
return fallback;
}
};
// Serialisieren ohne TypeError bei Zyklen oder BigInt
const safeStringify = (value, space) => {
const seen = new WeakSet(); // markiert auch mehrfach genutzte Referenzen
try {
return JSON.stringify(value, (k, v) => {
if (typeof v === 'bigint') return v.toString();
if (v && typeof v === 'object') {
if (seen.has(v)) return '[Circular]';
seen.add(v);
}
return v;
}, space);
} catch {
return undefined;
}
};
const obj = { id: 1n };
obj.self = obj;
console.log(safeStringify(obj));
console.log(safeParse('kaputt', {}));
{"id":"1","self":"[Circular]"}
{}