Skip to content

Commit 686287c

Browse files
authored
Merge pull request #78 from Rich-Harris/ignore-non-enumerable-symbols
ignore non-enumerable symbols
2 parents 7bbc088 + 1c50e79 commit 686287c

File tree

4 files changed

+24
-2
lines changed

4 files changed

+24
-2
lines changed

src/stringify.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
DevalueError,
3+
enumerable_symbols,
34
get_type,
45
is_plain_object,
56
is_primitive,
@@ -143,7 +144,7 @@ export function stringify(value, reducers) {
143144
);
144145
}
145146

146-
if (Object.getOwnPropertySymbols(thing).length > 0) {
147+
if (enumerable_symbols(thing).length > 0) {
147148
throw new DevalueError(
148149
`Cannot stringify POJOs with symbolic keys`,
149150
keys

src/uneval.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
DevalueError,
3+
enumerable_symbols,
34
escaped,
45
get_type,
56
is_plain_object,
@@ -89,7 +90,7 @@ export function uneval(value, replacer) {
8990
);
9091
}
9192

92-
if (Object.getOwnPropertySymbols(thing).length > 0) {
93+
if (enumerable_symbols(thing).length > 0) {
9394
throw new DevalueError(
9495
`Cannot stringify POJOs with symbolic keys`,
9596
keys

src/utils.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,10 @@ export function stringify_string(str) {
9797

9898
return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
9999
}
100+
101+
/** @param {Record<string | symbol, any>} object */
102+
export function enumerable_symbols(object) {
103+
return Object.getOwnPropertySymbols(object).filter(
104+
(symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable
105+
);
106+
}

test/test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,19 @@ const fixtures = {
390390
assert.equal(Object.getPrototypeOf(value), Object.prototype);
391391
assert.equal(Object.keys(value).length, 0);
392392
}
393+
},
394+
{
395+
name: 'non-enumerable symbolic key',
396+
value: (() => {
397+
const obj = { x: 1 };
398+
Object.defineProperty(obj, Symbol('key'), {
399+
value: 'value',
400+
enumerable: false
401+
});
402+
return obj;
403+
})(),
404+
js: '{x:1}',
405+
json: '[{"x":1},1]'
393406
}
394407
],
395408

0 commit comments

Comments
 (0)