Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support Date object serialization, make json more consistent with JSON.stringify #58

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ jsesc(['a', 'b', 'c'], {

#### `json`

The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore.
The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore. In general, the `json` flag attempts to mimick the coercion behavior of `JSON.stringify` - `Date` objects will be formatted as strings, `Set` objects will become empty objects `{}`, and `undefined` values in an array will become `null`.

```js
jsesc('foo\x00bar\xFF\uFFFDbaz', {
Expand Down Expand Up @@ -321,6 +321,9 @@ jsesc([ undefined, -Infinity ], {
'json': true
});
// → '[null,null]'

jsesc({ '!date': new Date(), '!set': new Set([1, 2])) });
// → {"!date":"2020-04-03T15:34:00.000Z","!set":{}}
```

**Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/).
Expand Down
10 changes: 8 additions & 2 deletions jsesc.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const isObject = (value) => {
// This is a very simple check, but it’s good enough for what we need.
return toString.call(value) == '[object Object]';
};
const isDate = (value) => {
return toString.call(value) == '[object Date]';
};
const isString = (value) => {
return typeof value == 'string' ||
toString.call(value) == '[object String]';
Expand Down Expand Up @@ -134,7 +137,7 @@ const jsesc = (argument, options) => {
}

if (!isString(argument)) {
if (isMap(argument)) {
if (!json && isMap(argument)) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A potential solution for #57; Map and Set don't have toJSON methods - and even if they did, they probably wouldn't return the same type, so the expectation here is that we never process a Map or Set in a special way when targetting JSON.

if (argument.size == 0) {
return 'new Map()';
}
Expand All @@ -144,7 +147,7 @@ const jsesc = (argument, options) => {
}
return 'new Map(' + jsesc(Array.from(argument), options) + ')';
}
if (isSet(argument)) {
if (!json && isSet(argument)) {
if (argument.size == 0) {
return 'new Set()';
}
Expand Down Expand Up @@ -205,6 +208,9 @@ const jsesc = (argument, options) => {
if (useOctNumbers) {
return '0o' + argument.toString(8);
}
} else if (isDate(argument)) {
// Date objects have a toJSON method, which implies json: false here.
return 'new Date(' + jsesc(argument.valueOf(), options) + ')';
} else if (!isObject(argument)) {
if (json) {
// For some values (e.g. `undefined`, `function` objects),
Expand Down
10 changes: 8 additions & 2 deletions src/jsesc.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ const isObject = (value) => {
// This is a very simple check, but it’s good enough for what we need.
return toString.call(value) == '[object Object]';
};
const isDate = (value) => {
return toString.call(value) == '[object Date]';
};
const isString = (value) => {
return typeof value == 'string' ||
toString.call(value) == '[object String]';
Expand Down Expand Up @@ -134,7 +137,7 @@ const jsesc = (argument, options) => {
}

if (!isString(argument)) {
if (isMap(argument)) {
if (!json && isMap(argument)) {
if (argument.size == 0) {
return 'new Map()';
}
Expand All @@ -144,7 +147,7 @@ const jsesc = (argument, options) => {
}
return 'new Map(' + jsesc(Array.from(argument), options) + ')';
}
if (isSet(argument)) {
if (!json && isSet(argument)) {
if (argument.size == 0) {
return 'new Set()';
}
Expand Down Expand Up @@ -205,6 +208,9 @@ const jsesc = (argument, options) => {
if (useOctNumbers) {
return '0o' + argument.toString(8);
}
} else if (isDate(argument)) {
// Date objects have a toJSON method, which implies json: false here.
return 'new Date(' + jsesc(argument.valueOf(), options) + ')';
mathiasbynens marked this conversation as resolved.
Show resolved Hide resolved
} else if (!isObject(argument)) {
if (json) {
// For some values (e.g. `undefined`, `function` objects),
Expand Down
50 changes: 50 additions & 0 deletions tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,18 @@ describe('common usage', function() {
'new Map([\n\t[\'a\', 1],\n\t[\'b\', new Map([\n\t\t[\'x\', 2],\n\t\t[\'y\', 3]\n\t])]\n])',
'Stringifying a Map with `compact: false`'
);
assert.equal(
jsesc(
new Map([
['a', 1]
]),
{
'json': true
}
),
'{}',
'Stringifying a Map with `json: true`'
);
assert.equal(
jsesc(
new Set([])
Expand Down Expand Up @@ -377,6 +389,19 @@ describe('common usage', function() {
'new Set([\n\t[\n\t\t\'a\'\n\t],\n\t\'b\',\n\t{}\n])',
'Stringifying a Set with `compact: false`'
);
assert.equal(
jsesc(
new Set([
['a'],
'b'
]),
{
'json': true
}
),
'{}',
'Stringifying a Set with `json: true`'
);
// Buffer
assert.equal(
jsesc(
Expand All @@ -395,6 +420,31 @@ describe('common usage', function() {
'Buffer.from([\n\t19,\n\t55,\n\t66\n])',
'Stringifying a Buffer with `compact: false`'
);
// Date
assert.equal(
jsesc(
new Date('2020-04-03T15:34:00Z')
),
'new Date(1585928040000)'
);
assert.equal(
jsesc(
new Date('2020-04-03T15:34:00Z'),
{
'numbers': 'hexadecimal'
}
),
'new Date(0x17140AD6E40)'
);
assert.equal(
jsesc(
new Date('2020-04-03T15:34:00Z'),
{
'json': true
}
),
'"2020-04-03T15:34:00.000Z"'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This depends on how we want to deal with #57, Is this what you'd expect when passing a Date/Map/Set while using json: true? Or would you want to throw an exception instead?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Either way this would need to be documented in the README under the json option.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the behavior of toJSON. I'd like to add an additional flag in a subsequent PR (or, I suppose, in this PR) to let the user override that behavior independent of the JSON mode.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could include an interpret option that accepts values like expect-json, coerce-json, and javascript to switch between the options. expect-json would throw on non-JSON-supported values; coerce-json would invoke toJSON and delegate to JSON.stringify's behavior in other cases; javascript would do its best to serialize all (non-circular) values for use in a js context.

I don't need expect-json for my own work, but coerce-json would be extremely useful. I've also been wondering if we could introduce a replacer-type option for both transforming and extending the supported values - e.g. we need strict coerce-json semantics, but also want to support the undefined value. If you're amenable to that, I'll see what that would take.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way I've used jsesc is always very controlled, in that: if there's a Date object, a Map, a Set, or a BigInt somewhere in the input, and I am requesting JSON output via json: true, that's probably a mistake. I've only used jsesc in cases where I want JSON.parse(output) to produce an equivalent object again.

So I defer to you on this. If you have a use case for it, that's great!

);
// JSON
assert.equal(
jsesc('foo\x00bar\xFF\uFFFDbaz', {
Expand Down