简体   繁体   中英

JSON.stringify changing properties

https://jsfiddle.net/6CDFr/229/

function testing() {
  foo = canvas.getObjects();
  bar = JSON.stringify(canvas.getObjects());
  console.log(foo);
  console.log(bar);
}

JSON.stringify() is altering the "x1","y1","x2" and "y2" properties, as detailed in my JSFiddle link above, and I'm not sure why.

From the (Mozilla) documentation for JSON.stringify ( https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior )

toJSON() behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized . For example:

If you use the following, you should get similar values

function testing() {
    foo = canvas.getObjects()[0];
    bar = JSON.stringify(canvas.getObjects()[0]);
    console.log(foo.toJSON());
    console.log(bar);
}

or if you set the toJSON property to undefined (but I'm pretty sure that's going to play havoc with fabric.js unless you do it on a copy of the object - I've done it directly on the object below)

function testing() {
    foo = canvas.getObjects();
    bar = JSON.stringify(canvas.getObjects().map(function (o) {
        o.toJSON = undefined;
        return o
    }));
    console.log(foo);
    console.log(bar);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM