JSON.stringify - How to get same result in all platforms when using circular objects?

Hi everyone!

I’m trying to store a variable containing an array of objects to the local storage of the device, in order to restore the state of that variable when the application restarts.
Because of the structure of the objects (tree with nodes kind of), they are circular because they contain references to the parent nodes. I spent quite a lot of time to make the code work and restore properly the state of the objects with their functions. Everything worked perfectly while I was testing it in the browser with the command ionic cordova run browser.

Unfortunately, apparently ionic serve, ionic cordova run android and ionic cordova run ios don’t work at all, because when I’m calling the JSON.stringify(this.data); on the variable that contains all the data, I get an error that the object is circular: ERROR TypeError: Converting circular structure to JSON.

What is different when I use the command ionic cordova run browser compared to the 3 above commands, and how can I have the same behavior on Android and iOS too (preferably without re-writing the code that I wrote)?

Using Smart-Circular and another solution that removed circular references didn’t work, as those are needed when restoring the data and somehow ionic cordova run browser handles it just fine.

Here are some information about my installation if it’s any use:


   ionic (Ionic CLI)  : 4.3.1 (xxx\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.0


   cordova (Cordova CLI) : 8.0.0
   Cordova Platforms     : android 7.0.0, browser 5.0.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.2.3, (and 20 other plugins)


   Android SDK Tools : 26.1.1 (yyy\Android\SDK)
   NodeJS            : v8.9.4 (xxx\nodejs\node.exe)
   npm               : 6.3.0
   OS                : Windows 7

Edit: After testing different plugins, now the error appears on ionic cordova run browser as well even though I removed them. I don’t wanna waste more time on researching or trying to reproduce the successful stringify call, so I’ll be working on a solution to remove the circular reference. But if anyone knows how, or what was the difference, please do post :slight_smile:

I’d recommend finding a dedicated library for serializing to/from JSON rather than just relying on the primitive built in stringify()

1 Like