Why can't JSON save object functions?

In my game, I save the current state by converting all objects to JSON, and then saving this to a file. Some objects, such as enemies, have functions on them, but JSON cannot save functions! Is there an alternative or solution?

+5
source share
2 answers
var Enemy = { toJSON: function () { // pack it up }, fromJSON: function (json) { // unpack it. }, /* methods */ }; var e = Object.create(Enemy); var json = JSON.stringify(e); var same_e = Enemy.fromJSON(json); 

The .toJSON method is the standard JSON.stringify interface, it will look for this method and call it, if it exists, it will truncate the returned object.

The .fromJSON method is just a named constructor for your Enemy object.

Concrete JSfiddle Example

 var Enemy = { constructor: function(name, health) { this.health = health || 100; this.name = name; }, shootThing: function (thing) { }, move: function (x,y) { }, hideBehindCover: function () {}, toJSON: function () { return { name: this.name, health: this.health }; }, fromJSON: function (json) { var data = JSON.parse(json); var e = Object.create(Enemy); e.health = data.health; e.name = data.name; return e; } } var e = Object.create(Enemy); e.constructor("bob"); var json = JSON.stringify(e); var e2 = Enemy.fromJSON(json); console.log(e.name === e2.name); 

Meta option:

The meta parameter would have to write the class name for the object

 Game.Enemy = { ... class: "Enemy" }; 

Then when you load all your json data, you just do

var instance = Game[json.class].fromJSON(json);

+7
source

I think you need to save the type on your object so that functions can be added repeatedly during parsing. For instance. put the type property on your enemy in the constructor. During parsing, first parse the string like regular JSON, and then go deep into the resulting object. When you come across what Enemy , reattach the methods or so.

+1
source

Source: https://habr.com/ru/post/918248/


All Articles