montagejs / collections

This package contains JavaScript implementations of common data structures with idiomatic interfaces.
http://www.collectionsjs.com
Other
2.1k stars 183 forks source link

Can these be applied via JSON? #81

Closed zoomclub closed 10 years ago

zoomclub commented 10 years ago

I'm de/serializing data structures as JSON. How would these alternate collections be used with JSON documents? For instance, if I would choose the enhanced array how would a JSON deserializer know that it should instantiate the enhanced array versus the standard array?

Stuk commented 10 years ago

JSON can only serialize/deserialize objects that have Object.prototype as their prototype, i.e. not objects that "inherit" from another class. In the case of an array it's not a problem, as if you require("shim-array") on both sides then the array will have all of the methods.

For other collections, such as a Map, you'll have to write your own serialization/deserialization wrapper. To get the collection in a serializable format you can use .toArray() for lists/sets, and .entries() for maps with objects as keys. For deserialization you can pass the result of these functions into the appropriate constructor.

kriskowal commented 10 years ago

We do need to implement toJSON on all collections. This should be relatively trivial. Map needs to delegate to entries() and others need to delegate to toArray() or toObject(). So we could serialize to JSON. Deserializing from JSON is another matter. In all cases, you would be able to reverse the effects of toJSON with the corresponding collection constructor, e.g., new Map(map.toJSON()) should always work, but object graphs with cycles and encoding and decoding what collection to deserialize in JSON is beyond the scope of this project.

zoomclub commented 10 years ago

Glad to learn that there will be JSON de/serialize support. Is it possible to show how this will work with a demo on your site or download? If that works then I'll be well on the way to encoding and decoding the object graph I have have in mind.

Stuk commented 10 years ago

This pull request should address your issue: https://github.com/montagejs/collections/pull/87

Stuk commented 10 years ago

Fixed in Collections v1.2.1, and documented at http://www.collectionsjs.com/method/to-json

zoomclub commented 10 years ago

Thanks, this now bridges the complete IO circle, wonderful!