From 4a8c4568fe6bf85daf6f473aaa50007c43f74d6e Mon Sep 17 00:00:00 2001 From: Jordan Tucker Date: Thu, 6 Jun 2019 10:27:37 -0500 Subject: [PATCH] fix: add __proto__ to objects and arrays --- CHANGELOG.md | 5 +++++ lib/parse.js | 41 ++++++++++++++++++++++++++++++++++------- test/parse.js | 6 ++++++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e0ce0b3..e9478ec2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,10 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Unicode 10 to 14. - `package.json5` is included in the npm package. +### Fixes + +- Properties with the name `__proto__` are added to objects and arrays. ([#199]) + ## v2.2.1 - 2022-03-21 ### Fixes @@ -328,6 +332,7 @@ parser for the regular JSON format. [#182]: https://github.com/json5/json5/issues/182 [#187]: https://github.com/json5/json5/issues/187 [#196]: https://github.com/json5/json5/issues/196 +[#199]: https://github.com/json5/json5/issues/199 [#208]: https://github.com/json5/json5/issues/208 [#210]: https://github.com/json5/json5/issues/210 [#222]: https://github.com/json5/json5/issues/222 diff --git a/lib/parse.js b/lib/parse.js index 0734bdc8..44e7585a 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -42,12 +42,34 @@ module.exports = function parse(text, reviver) { function internalize(holder, name, reviver) { const value = holder[name] if (value != null && typeof value === 'object') { - for (const key in value) { - const replacement = internalize(value, key, reviver) - if (replacement === undefined) { - delete value[key] - } else { - value[key] = replacement + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + const key = String(i) + const replacement = internalize(value, key, reviver) + if (replacement === undefined) { + delete value[key] + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }) + } + } + } else { + for (const key in value) { + const replacement = internalize(value, key, reviver) + if (replacement === undefined) { + delete value[key] + } else { + Object.defineProperty(value, key, { + value: replacement, + writable: true, + enumerable: true, + configurable: true, + }) + } } } } @@ -968,7 +990,12 @@ function push() { if (Array.isArray(parent)) { parent.push(value) } else { - parent[key] = value + Object.defineProperty(parent, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }) } } diff --git a/test/parse.js b/test/parse.js index 6491fa53..ba9b0fd4 100644 --- a/test/parse.js +++ b/test/parse.js @@ -38,6 +38,12 @@ t.test('parse(text)', t => { 'parses escaped property names', ) + t.strictSame( + JSON5.parse('{"__proto__":1}').__proto__, + 1, + 'preserves __proto__ property names', + ) + t.strictSame( JSON5.parse('{abc:1,def:2}'), {abc: 1, def: 2},