This error message «TypeError: Converting circular structure to JSON» typically occurs when you try to stringify an object that contains circular references using JSON.stringify().
A circular reference occurs when an object references itself in some way. For example, consider the following code:
const obj = { foo: {} };
obj.foo.obj = obj;
In this example, obj contains a circular reference because the foo property of obj contains a reference to obj itself.
When you try to stringify an object like this using JSON.stringify(), it will fail with the error message «TypeError: Converting circular structure to JSON».
To solve this issue, you can use a third-party library like flatted or circular-json, which are specifically designed to handle circular references in JavaScript objects. Here’s an example using flatted:
const flatted = require('flatted');
const obj = { foo: {} };
obj.foo.obj = obj;
const str = flatted.stringify(obj);
console.log(str);
In this example, we use flatted.stringify() instead of JSON.stringify(), and it successfully converts the object to a string without throwing an error.
Alternatively, you can modify your object to remove the circular reference before trying to stringify it. For example:
const obj = { foo: {} };
obj.foo.bar = 'baz';
// add circular reference
obj.foo.obj = obj;
// remove circular reference
obj.foo.obj = undefined;
const str = JSON.stringify(obj);
console.log(str);
In this example, we add the circular reference and then remove it before trying to stringify the object. This approach works well if you don’t need to preserve the circular reference in the stringified object.
I think I speak for everyone who is a newbie at JavaScript or is currently studying JavaScript when I say there is nothing more frustrating than attempting to find the error in your code and still not being able to do it after trying for hours. Even after spending hours looking at the same lines of code, you can still miss the error. But as any seasoned programmer will tell you, the secret to identifying the issue is to sit back and look at the big picture and the overall flow of the program. Of course, there are situations when, despite your best efforts, you cannot understand the error in your code. If you are getting the error “TypeError: Converting circular structure to JSON in JS” you’ve come to the right place. In this blog, we will discuss what exactly a Type Error is, how it can occur in Java Script and how to get rid of it for good.
What exactly is TypeError?
Let us first learn how JavaScript errors work in order to understand TypeError. In addition to logical errors, JavaScript also has two more sorts of errors: runtime errors and syntax errors (we commonly call them exceptions).
Syntax errors occur when the compiler detects an incorrect statement. However, TypeError in this instance is a runtime issue. When software crashes even though the syntax is correct, it is most probably a runtime error. Depending on the kind of error the program encounters, there are all kinds of runtime errors, including TypeError.
When an exception occurs, along with the error message, the kind of exception your program encountered (in this case, TypeError) is shown in the output. “Converting circular structure to JSON” is the error message that appears in our situation, telling us that there is a problem with the object we are trying to convert to JSON. When we attempt to access or pass a method or property of an unexpected type, we encounter a TypeError.
When does this error occur?
This error occurs when you try to convert a JavaScript object to JSON, but the object contains a circular reference. A circular reference occurs when an object refers to itself, directly or indirectly. For example, imagine you have a JavaScript object with a property that references the object itself:
Code language: JavaScript (javascript)
let obj = { name: "Codedamn", parent: null } obj.parent = obj;
In this case, the obj object contains a circular reference because the parent property references the obj object. When you try to convert this object to JSON, you’ll get the “TypeError: Converting circular structure to JSON” error because JSON.stringify()
(the method used to convert JavaScript objects to JSON) doesn’t support circular references.
The solution
Thankfully, the solution to this TypeError problem is pretty straightforward. To fix this error, you need to make sure that your objects don’t contain circular references. One way to do this is to use a library like JSONC that supports converting circular structures to JSON. Alternatively, you can manually detect and remove circular references from your objects before calling JSON.stringify()
.
Here is a simple code snippet that will let you ignore properties with circular references in an object:
Code language: JavaScript (javascript)
function stringify(obj) { let cache = []; let str = JSON.stringify(obj, function(key, value) { if (typeof value === "object" && value !== null) { if (cache.indexOf(value) !== -1) { // Circular reference found, discard key return; } // Store value in our collection cache.push(value); } return value; }); cache = null; // reset the cache return str; }
In this function, we use the JSON.stringify()
method’s second argument (the replacer function) to detect and remove circular references from the object before converting it to JSON. We do this by keeping track of all the objects we have seen in a cache array and checking if the current value is already in the cache. If it is, we return undefined
to remove the value from the final JSON string.
With this function, you can safely convert objects with circular references to JSON without getting the “TypeError: Converting circular structure to JSON” error. Just remember to use this function instead of JSON.stringify()
whenever you need to convert an object to JSON.
Conclusion
The first thing you should do when you encounter an issue is to Google it. It’s likely that another programmer has already dealt with this problem and found a solution! You may make it easier to debug your code by organizing it and adding comments. It is frequently helpful to print out the values of variables during debugging to identify the issue. In order to discover and correct mistakes, you can also use a debugging tool like a linter or a debugger. In this article, we understood the meaning of the error message “TypeError: Converting circular structure to JSON”. We looked at when this error message might occur and the possible actions you can take to get rid of it. I hope this article has cleared all your doubts regarding circular structures, and how it can be a problem with the JSON.stringify()
method.
If you have any questions regarding this article or want to talk about anything technology, you can find me on Twitter. Thank you for reading!
Become The Best JavaScript Developer 🚀
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice JavaScript courses, labs, and become employable full-stack JavaScript web developer.
Free money-back guarantee
Unlimited access to all platform courses
100’s of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Start Learning
Время на прочтение
5 мин
Количество просмотров 398K
JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!
Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.
Как читать ошибки?
Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.
Типичная ошибка из Chrome выглядит так:
Uncaught TypeError: undefined is not a function
Структура ошибки следующая:
- Uncaught TypeError: эта часть сообщения обычно не особо полезна.
Uncaught
значит, что ошибка не была перехвачена вcatch
, аTypeError
— это название ошибки. - undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение
undefined
как функцию.
Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.
Теперь к самим ошибкам.
Uncaught TypeError: undefined is not a function
Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected
Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:
var foo = undefined;
foo();
Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.
var x = document.getElementByID('foo');
Несуществующие свойства объекта по-умолчанию имеют значение undefined
, что приводит к этой ошибке.
Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.
Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.
Uncaught ReferenceError: Invalid left-hand side in assignment
Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’
Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.
Наиболее частый пример этой ошибки — это условие в if:
if(doSomething() = 'somevalue')
В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.
Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this
.
Uncaught TypeError: Converting circular structure to JSON
Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported
Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify
.
var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);
Так как a
и b
в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.
Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.
Unexpected token ;
Связанные ошибки: Expected ), missing ) after argument list
Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.
Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.
Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.
Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.
Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.
Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.
Uncaught SyntaxError: Unexpected token ILLEGAL
Связанные ошибки: Unterminated String Literal, Invalid Line Terminator
В строковом литерале пропущена закрывающая кавычка.
Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.
Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference
Попытка прочитать null
или undefined
так, как будто это объект. Например:
var someVal = null;
console.log(someVal.foo);
Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.
Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined
Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference
Попытка записать null
или undefined
так, как будто это объект. Например:
var someVal = null;
someVal.foo = 1;
Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.
Uncaught RangeError: Maximum call stack size exceeded
Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow
Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.
Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.
Uncaught URIError: URI malformed
Связанные ошибки: URIError: malformed URI sequence
Вызвано некорректным вызовом decodeURIComponent
.
Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.
XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource
Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url
Эта проблема всегда связана с использованием XMLHttpRequest.
Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Связанные ошибки: InvalidStateError, DOMException code 11
Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest
при попытке вызвать на нём функции до его готовности.
var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');
В данном случае вы получите ошибку потому, что функция setRequestHeader
может быть вызвана только после вызова xhr.open
.
Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open
).
Заключение
JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM
в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.
Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.
P.S. Этот перевод можно улучшить, отправив PR здесь.
We’re seeing this issue but, extending the above example, it’s the err.request._currentRequest._redirectable
which is a circular reference.
request: Writable { ... _currentRequest: ClientRequest { domain: null, _events: [Object], _eventsCount: 6, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: false, _headerSent: true, socket: [Object], connection: [Object], _header: '...', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '...', _ended: false, _redirectable: [Circular], // <---- parser: null }, _currentUrl: '...' }, response: undefined }
Trusted answers to developer questions
Grokking the Behavioral Interview
Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.
TypeError: Converting circular structure to JSON occurs when you try to reference your variable name within the JSON object.
var mycar ={}
mycar.a = mycar
JSON.stringify(mycar)
The code above will give an error since JSON.stringify
is unable to convert such structures. This also happens to DOM nodes with circular references.
Solutions
1. Removing dependencie
Try to remove any circular dependencies that have been created in the code.
2. Use the flatted package
You can use the flatted package to solve the issue. Take a look at the example code given below:
const {parse, stringify} = require('flatted/cjs');
const mycar = {};
mycar.a = mycar;
stringify(mycar);
console.log(mycar)
3. Remove the console.logs
At times, printing a value that has already been referenced might create circular dependency. However, if you remove such print statements, and the code should work.
Copyright ©2023 Educative, Inc. All rights reserved
Learn in-demand tech skills in half the time
Copyright ©2023 Educative, Inc. All rights reserved.
Did you find this helpful?