Last active
February 23, 2021 09:42
-
-
Save EmileSonneveld/fd0e3ee77932e978d61789b0a9e51a0f to your computer and use it in GitHub Desktop.
no references in JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This illustrates that serialising to JSON loses information. | |
var obj = { | |
ref1: {foo:"bar"}, | |
} | |
obj.ref2 = obj.ref1 | |
console.log(obj) | |
obj.ref2.foo = "changed" | |
console.log(obj) // both changed | |
obj2 = JSON.parse(JSON.stringify(obj)) | |
obj2.ref1.foo = "changed again" | |
console.log(obj2) // only one changed | |
// In the perfect world, this function would exist: | |
function serialise(objArgument) { | |
let str = 'var o = ' + JSON.stringify(obj) | |
str += '; o.ref2 = o.ref1; o;' // hack, for now. | |
return str | |
} | |
function deserialise(objStr) { | |
// if objStr comes from the backend, the backend could assure it contains no hacks by doing | |
// assert(objStr === serialise(deserialise(objStr))) | |
return eval(objStr) | |
} | |
var str = serialise(obj) | |
console.log(str) | |
var deserialisedObj = deserialise(str) | |
console.log(deserialisedObj) | |
deserialisedObj.ref1.foo = "changed" // will change the object behind the 2 refs. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More concrete example: commenthol/serialize-to-js#18