0

When trying to save some data about the game world in a file using JSON, I get that good ol' JSON circular reference error. Is there a way to save circular data types? Also, I'm running this with node.js, not inside a browser.

Basically, over time, the player gets some units. These units are saved to a list inside the player object, but are given the player himself as an argument, so they know who's their owner. Something like this:

Player = function()
{
    this.power = 0
    this.units = [new Unit(this)];
}

Unit = function(owner)
{
    owner.power++;   
}
corazza
  • 31,222
  • 37
  • 115
  • 186
  • You can't serialize a circular reference, can you maybe reference an id instead? – Joe Sep 27 '11 at 15:30
  • 1
    There are serialisation libraries that solve this problem for you: https://github.com/douglascrockford/JSON-js – davin Sep 27 '11 at 15:32
  • possible duplicate of [Javascript: How to save an object with circular references?](http://stackoverflow.com/questions/7420597/javascript-how-to-save-an-object-with-circular-references) – davin Sep 27 '11 at 15:32
  • Hey, that cycle.js file seems to be what I need, but how do I include it in my code? – corazza Sep 27 '11 at 15:57
  • Hey, editing that code is way out of my league, I don't get half of the syntax and it's hard to read... Would you care to give me some tips on where to put the "exports" prefix please? – corazza Sep 27 '11 at 19:43

1 Answers1

1

@Bane, in answer to how to include the cycle.js

Put it in your lib folder for your project and include it via a script tag if you're doing it on the client side.

On the server side you could include the code in the file that you need the circular reference in; that's simple but really the wrong way to work. Better bet is to build it out as a module, check this tutorial on howtonode.org for the specifics.

Your overall best bet though is to refactor so that you don't need the circular reference.

Logos
  • 238
  • 1
  • 5
  • So, the basic idea is that I have to edit the cycle.js file, adding the "export" prefix to those two functions? – corazza Sep 27 '11 at 17:08
  • 1
    Mostly, I didn't check the cycle.js file thoroughly so I'm not 100% sure if it depends on anything else. But otherwise, yeah basically. Also, it uses jsonPath so you'll want to npm install jsonpath [here's the git](https://github.com/temsa/jsonpath) Looks like it would work after that. – Logos Sep 27 '11 at 17:19
  • Ok, thanks, I'm gonna give it a try tomorrow and get you back. I'm having some troubles with positioning system, so I just commented out the part where it saves the game, gonna deal with it later. – corazza Sep 27 '11 at 18:32