Skip to content

Commit

Permalink
Fix Issue mathiasbynens#17: "remove differences between `jsesc(data, …
Browse files Browse the repository at this point in the history
…{ json: true })` and `JSON.stringify(data)"
  • Loading branch information
sonneveld committed Aug 17, 2014
1 parent a4368cc commit d652c4f
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions jsesc.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
return typeof value == 'string' ||
toString.call(value) == '[object String]';
};
var isFunction = function(value) {
return typeof value == 'function';
};

/*--------------------------------------------------------------------------*/

Expand Down Expand Up @@ -108,6 +111,11 @@
var result;
var isEmpty = true;

// convert argument to toJSON if needed.
if (json && argument && isObject(argument) && isFunction(argument.toJSON)) {
argument = argument.toJSON();
}

if (!isString(argument)) {
if (isArray(argument)) {
result = [];
Expand Down
8 changes: 8 additions & 0 deletions src/jsesc.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
return typeof value == 'string' ||
toString.call(value) == '[object String]';
};
var isFunction = function(value) {
return typeof value == 'function';
};

/*--------------------------------------------------------------------------*/

Expand Down Expand Up @@ -108,6 +111,11 @@
var result;
var isEmpty = true;

// convert argument to toJSON if needed.
if (json && argument && isObject(argument) && isFunction(argument.toJSON)) {
argument = argument.toJSON();
}

if (!isString(argument)) {
if (isArray(argument)) {
result = [];
Expand Down
11 changes: 11 additions & 0 deletions tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,17 @@
'"foo\\u{1D306}bar\\u00A9baz"',
'Escaping as JSON with `es6: true`'
);
equal(
jsesc('foo - \uD83D\uDCA9 - foo', {json: true}),
'"foo - \\uD83D\\uDCA9 - foo"',
'Escaping as JSON is same as JSON.stringify'
);
var objWithToJson = {'shouldnt be here': 10, toJSON: function() { return {'hello': 'world', 'cat': 'dog', 'pileof': '\uD83D\uDCA9'}; }};
equal(
jsesc(objWithToJson, {json: true}),
'{"hello":"world","cat":"dog","pileof":"\\uD83D\\uDCA9"}',
'Escaping obj with toJSON, as JSON, is same as JSON.stringify'
);
});

if (runExtendedTests) {
Expand Down

0 comments on commit d652c4f

Please sign in to comment.