Broken code example
const user = {};
user.self = user;
JSON.stringify(user);Corrected example
const user = {};
JSON.stringify(user);Why this error happens
JSON does not have a native way to represent an object that points back to itself. When JSON.stringify discovers that cycle, it throws instead of producing invalid or misleading output.
How to fix it
- Remove the circular reference if it is not needed.
- Create a plain serializable copy of the object.
- Use a custom replacer when you intentionally want to skip circular branches.
- Then validate or format the resulting JSON string if needed.