Skip to content

Instantly share code, notes, and snippets.

@EmileSonneveld
Last active February 23, 2021 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmileSonneveld/fd0e3ee77932e978d61789b0a9e51a0f to your computer and use it in GitHub Desktop.
Save EmileSonneveld/fd0e3ee77932e978d61789b0a9e51a0f to your computer and use it in GitHub Desktop.
no references in JSON
// 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.
@EmileSonneveld
Copy link
Author

More concrete example: commenthol/serialize-to-js#18

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment