From 98a96e1d48213e24fb8c878caa267e26cf843a90 Mon Sep 17 00:00:00 2001 From: egargan Date: Wed, 27 Oct 2021 15:35:41 +0100 Subject: [PATCH] add 'objectProto' option to create parsed objects as {} This gives clients the ability to go back to the old behaviour before c85a430, where any parsed object was created as {}. --- lib/parse.js | 6 +++++- test/object-proto-test.js | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 test/object-proto-test.js diff --git a/lib/parse.js b/lib/parse.js index 84d142f..085880b 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -84,6 +84,7 @@ var json_parse = function (options) { var _options = { strict: false, // not being strict means do not generate syntax errors for "duplicate key" storeAsString: false, // toggles whether the values should be stored as BigNumber (default) or a string + objectProto: false, // toggles whether to parse objects as Objects (consistent with JSON.parse), or as null-prototype objects alwaysParseAsBig: false, // toggles whether all numbers should be Big useNativeBigInt: false, // toggles whether to use native BigInt instead of bignumber.js protoAction: 'error', @@ -98,6 +99,9 @@ var json_parse = function (options) { if (options.storeAsString === true) { _options.storeAsString = true; } + if (options.objectProto === true) { + _options.objectProto = true; + } _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; _options.useNativeBigInt = @@ -328,7 +332,7 @@ var json_parse = function (options) { // Parse an object value. var key, - object = Object.create(null); + object = _options.objectProto ? {} : Object.create(null); if (ch === '{') { next('{'); diff --git a/test/object-proto-test.js b/test/object-proto-test.js new file mode 100644 index 0000000..04a0ae1 --- /dev/null +++ b/test/object-proto-test.js @@ -0,0 +1,22 @@ +const makeJSON = require('../index.js'); +const expect = require('chai').expect; + +describe('objectProto option', function(){ + it("should parse objects as Object instances if 'objectProto' set to true", function(done){ + const JSONbigObjectProto = makeJSON({ objectProto: true }); + var json_with_object = '{ "foo": { "bar": "baz" }}'; + var result = JSONbigObjectProto.parse(json_with_object); + expect(result instanceof Object).to.be.true; + expect(result['foo'] instanceof Object).to.be.true; + done(); + }); + + it("should parse objects as null-prototype objects if 'objectProto' set to false", function(done){ + const JSONbigNullProto = makeJSON({ objectProto: false }); + var json_with_object = '{ "foo": { "bar": "baz" }}'; + var result = JSONbigNullProto.parse(json_with_object); + expect(result.__proto__).to.be.undefined; + expect(result['foo'].__proto__).to.be.undefined; + done(); + }); +});