sidorares / json-bigint

JSON.parse/stringify with bigints support
MIT License
790 stars 189 forks source link

Add `objectBaseClass` option which can be set to `Object` instead of `null` to keep prototype methods like `hasOwnProperty` #47

Open klesun opened 3 years ago

klesun commented 3 years ago

As discussed in https://github.com/sidorares/json-bigint/issues/38, after the c85a4300aa0159ce1859c1b1adfdac9e515e5396 (v1.0.0) base class for parsed objects is now null rather than Object. This differs from the JSON.parse() behaviour and breaks compatibility for codebases that are using prototype methods like hasOwnProperty().

By specifying the objectBaseClass option introduced in this PR, users of the lib will be able to use it even in a code that relies on parsed object to have hasOwnProperty, toString and other prototype methods:

var JSONbig = require('json-bigint');
var JSONBigInt = JSONbig({ objectBaseClass: Object }); // default is null
var json = '{ "value" : 9223372036854775807, "v2": 123 }';
// does not result in "hasOwnProperty is not a function" TypeError thanks to `objectBaseClass: Object`
console.log(JSONBigInt.parse(json).hasOwnProperty("value"));

Closes #39, #38

egargan commented 2 years ago

Anything stopping this being merged??

egargan commented 2 years ago

Anything stopping this being merged??

Ah because it doesn't actually do anything! The 'objectBaseClass' option isn't actually applied to the _options variable that parse reads from.

I've just opened #64 with a similar fix. It won't let you provide an arbitrary prototype for the parsed objects, but it will let you choose between Object.create(null) and {}.