Sets plus JSON

Rick Waldron waldron.rick at gmail.com
Wed Oct 3 10:12:48 PDT 2012


On Wed, Oct 3, 2012 at 12:56 PM, Herby Vojčík <herby at mailbox.sk> wrote:

>
>
> Nicholas C. Zakas wrote:
>
>> After a little more experimenting with sets (still a really big fan!!),
>> I've come across an interesting problem. Basically, I found myself using
>> a set and then wanting to convert that into JSON for storage.
>> JSON.stringify() run on a set returns "{}", because it's an object
>> without any enumerable properties. I'm wondering if that's the correct
>> behavior because a set is really more like an array than it is an
>> object, and perhaps it would be best to define a toJSON() method for
>> sets such as:
>>
>> Set.prototype.toJSON = function() {
>> return Array.from(this);
>>
> It depends... you should be able to reread it, so the best thing would
> proably be to use matching set of transformers for both stringify and
> parse. I personally would rather see something like
>         { _Set_from_: Array.from(this) }
> here.
>
>  };
>>
>

The revived array can be passed as an arg to new Set(revived) :

new Set(JSON.parse(s.toJSON()))

Introducing another Set constructor just to wrap the above is early-warning
feature creep. toJSON is an intuitive addition

Rick







>
>> That way, JSON.stringify() would do something rational by default when
>> used with sets.
>>
>> Thoughts?
>>
>> Thanks,
>> Nicholas
>>
>
> Herby
>
> P.S.: It would be helpful, however, to include JSON helpers for wrapping
> sets, maps etc. in some module; but it can be a library, no need to use
> spec for this.
>
> ______________________________**_________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/**listinfo/es-discuss<https://mail.mozilla.org/listinfo/es-discuss>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20121003/d01e344a/attachment-0001.html>


More information about the es-discuss mailing list