From 0f922d2b1a8754f35754b32d7351294f695b3e1a Mon Sep 17 00:00:00 2001 From: Takuto Wada Date: Mon, 5 Feb 2024 17:28:34 +0900 Subject: [PATCH 1/2] test: add reproduction case for symbol as object key --- test/es6_test.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/es6_test.js b/test/es6_test.js index 698fe92..1ce40b4 100644 --- a/test/es6_test.js +++ b/test/es6_test.js @@ -9,4 +9,12 @@ describe('ES6 features', () => { it('Symbol', () => { assert.strictEqual(stringify(FOO), 'Symbol(FOO)'); }); + it('Symbol as Object key', () => { + const id = Symbol("id"); + const user = { + name: "John", + [id]: 123 + }; + assert.strictEqual(stringify(user), 'Object{name:"John",Symbol(id):123}'); + }); }); From 2f3b9b4e4c4f4f84374353545effa6c122ee5d04 Mon Sep 17 00:00:00 2001 From: Takuto Wada Date: Mon, 5 Feb 2024 17:29:21 +0900 Subject: [PATCH 2/2] fix: support symbol as object key --- index.js | 2 +- strategies.js | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index ae648ed..61ab14a 100644 --- a/index.js +++ b/index.js @@ -53,7 +53,7 @@ function createStringifier (customOptions) { return function stringifyAny (push, x) { const context = this; let handler = handlerFor(context.node, options, handlers); - const currentPath = '/' + context.path.join('/'); + const currentPath = '/' + context.path.map(String).join('/'); const customization = handlers[currentPath]; const acc = { context: context, diff --git a/strategies.js b/strategies.js index d26ed03..2421513 100644 --- a/strategies.js +++ b/strategies.js @@ -244,7 +244,11 @@ function decorateObject () { } function sanitizeKey (key) { - return /^[A-Za-z_]+$/.test(key) ? key : JSON.stringify(key); + if (typeof key === 'symbol') { + return key.toString(); + } else { + return /^[A-Za-z_]+$/.test(key) ? key : JSON.stringify(key); + } } function afterAllChildren (context, push, options) {