From d652c4fcced588e54bcd4d0670006306ffe1d6bc Mon Sep 17 00:00:00 2001 From: Nick Sonneveld Date: Tue, 22 Jul 2014 11:32:31 +1000 Subject: [PATCH] Fix Issue #17: "remove differences between `jsesc(data, { json: true })` and `JSON.stringify(data)" --- jsesc.js | 8 ++++++++ src/jsesc.js | 8 ++++++++ tests/tests.js | 11 +++++++++++ 3 files changed, 27 insertions(+) diff --git a/jsesc.js b/jsesc.js index 56241b4..0553a64 100644 --- a/jsesc.js +++ b/jsesc.js @@ -58,6 +58,9 @@ return typeof value == 'string' || toString.call(value) == '[object String]'; }; + var isFunction = function(value) { + return typeof value == 'function'; + }; /*--------------------------------------------------------------------------*/ @@ -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 = []; diff --git a/src/jsesc.js b/src/jsesc.js index 2239e44..24c49a0 100644 --- a/src/jsesc.js +++ b/src/jsesc.js @@ -58,6 +58,9 @@ return typeof value == 'string' || toString.call(value) == '[object String]'; }; + var isFunction = function(value) { + return typeof value == 'function'; + }; /*--------------------------------------------------------------------------*/ @@ -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 = []; diff --git a/tests/tests.js b/tests/tests.js index b183038..c3da96b 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -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) {