4

ES6/Harmony introduces new data types for Maps and Sets. Is there anyway to load JSON into those types instead of the default Object and Array?

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468

2 Answers2

3

Set does not have the same meaning as Array. A set is a collection of unique items while an array is an ordered collection of items that are not necessarily unique.

To load JSON into a map instead of an associative array, look at JSON.parse. You can write a custom resolver, like so:

JSON.parse(json, (k, v) => {
        if(typeof v == 'object' && !(v instanceof Array))
            return new Map(Object.entries(v));
        return v;
    });

Map takes an iterator of key value pairs, so we need to pass the value through Object.entries first. Object.entries is a planned feature that has not been finalized yet by the looks of it. Here is an implementation:

Object.entries = function* entries(obj) {
   for (let key of Object.keys(obj)) {
     yield [key, obj[key]];
   }
}

(They might instead decide on Object.prototype.entries in which case the code would look slightly different.)

lyschoening
  • 18,170
  • 11
  • 44
  • 54
0

I'm not entirely sure what you mean by "loading JSON into those types". I assume parsing its object literals as maps and array literals as sets?

In any case, the answer is no. JSON does not change with ES6, nor does the API of the standard JSON object. However, you can of course convert the result of JSON.parse into a map-based representation yourself quite easily.

Andreas Rossberg
  • 34,518
  • 3
  • 61
  • 72
  • 1
    Right, but (a) why wouldn't it change? If JSON is primarily concerned with object portability shouldn't most languages more closely implement they're "Object Syntax" as ES6 Maps, and their Array syntax as ES6 Sets. Aren't those better matches when prototypes don't matter and you do not want inheritance... – Evan Carroll Mar 01 '14 at 07:09
  • Of course one could imagine new functionality, i.e., a separate parse function that creates maps and sets. But nobody has made a proposal for that. Whether it is more adequate depends on the use case. Note in particular that, while all JSON objects could be parsed into maps, the inverse is not true: maps with non-string keys have no JSON representation. Arguably, that makes such a mapping less natural. Also, JSON often is used simply as a serialisation format for JS objects. – Andreas Rossberg Mar 01 '14 at 07:49
  • writing out an ecmascript 6 Map to JSON (stringify), it just looks like an object. When reading that same stringified representation from JSON (string) back into Object (parse) it loses all knowledge that it was previously an object with a Map. – arcseldon Jul 14 '14 at 08:35