Proposal: add an option to omit prototype of objects created by JSON.parse()

Danielle McLean gopsychonauts at gmail.com
Wed Sep 28 14:59:15 UTC 2016


From: 段垚 (mailto:duanyao at ustc.edu)
Date: 28 September 2016 at 16:36:52

> [I]mplementors warn that mutating prototype causes "performance
> hazards".

You don't actually need to mutate any prototypes to get prototypeless
objects out of `JSON.parse` - the reviver function is allowed to
return a new object instead, so you can create a fresh one with the
correct prototype. For example:

```js
JSON.parse(string, function(k, v) {
  if (v && typeof v === 'object' && !Array.isArray(v)) {
    return Object.assign(Object.create(null), v);
  }
  return v;
});
```

> How about adding an option to omit prototype of objects created by
> JSON.parse()?
>
> JSON.parse(str, { noPrototype: true });

While you can achieve the appropriate result already without extra
language support, I think this particular situation is common enough
that such an option might be a good idea.

How would you expect this new parameter to interact with the existing
second parameter to `JSON.parse`, the reviver function? I'd suggest
that the cleanest way to add the options would be for the second
parameter to be either an object or function, like this:

```js
JSON.parse(str, someFunc);
// equivalent to
JSON.parse(str, {reviver: someFunc});
```

Another approach would be to use two separate optional parameters,
i.e., `JSON.parse(text[, reviver][, options])`, but generally that
style is very messy.


More information about the es-discuss mailing list