Skip to content

Instantly share code, notes, and snippets.

@Me1000
Created August 17, 2012 23:57
Show Gist options
  • Save Me1000/3383530 to your computer and use it in GitHub Desktop.
Save Me1000/3383530 to your computer and use it in GitHub Desktop.
x = {
name: "x"
};
y = {
name: "y",
a: x
};
z = {
name: "z",
a: x,
b: y
};
x.b = y;
x.c = z;
y.b = z;
// When encoding x using https://gist.github.com/3373779 the output of the JSON is:
{
"name": "x",
"b": {
"name": "y",
"b": {
"name": "z"
}
},
"c": {
"name": "z",
"b": {
"name": "y"
}
}
}
// with a tree that looks like:
x
/ \
y z
/ \
z y
// An entierly different representation of the data you want to encode.
// Honestly it seems like more times than not, it would be frustrating to work with
// Because you can never get the original data back.
// I propose this format would be more useful:
{
objects:{"$0": {"name": "x", "b": "__SERIALIZER__$1", "c": "__SERIALIZER__$2"},
"$1": {"name": "y", "a": "__SERIALIZER__$0", "b": "__SERIALIZER__$2"},
"$2": {"name": "z", "a": "__SERIALIZER__$0", "b": "__SERIALIZER__$1"}
},
version: "JSONGraphSerializer1.0"
}
// The main advantage here is that you can always get the original object graph back in memory.
// While this basic example does output a larger string, the actual size of the
// JSON will always be linear with respect to the number of objects encoded.
// The circular ref remover will grow at a greater rate depending on how deep you
// have to go to find the circles in the graph.
// The disadvantage here is that if you're a crazy person and name an object
// attribute '__SERIALIZER__$0' then things get really messy.
@getify
Copy link

getify commented Aug 18, 2012

Given the top down approach the serialization of view would throw away button.controller, but I can't think of a situation where that data wouldn't be important. Likewise, if you serialized button instead of view you get an array missing items... I can think of a lot of situations where that would confuse me...

See the second point I made in this comment: https://gist.github.com/3373779#gistcomment-400333

@getify
Copy link

getify commented Aug 18, 2012

BTW, this seems right up your alley: https://github.com/douglascrockford/JSON-js/blob/master/cycle.js

It's not suitable for me, for the reasons I express here: https://github.com/douglascrockford/JSON-js/issues/39#issuecomment-7845004

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