Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
feat(Angular.js): skip JSON.stringify for undefined
Browse files Browse the repository at this point in the history
Return early in `angular.toJson` if the object to be stringified is `undefined`.
IE8 stringifies `undefined` to `'undefined'` whereas other browsers return
`undefined`. This normalizes behavior and passes currently broken unit tests
in IE8.
  • Loading branch information
xdissent authored and pkozlowski-opensource committed Jul 12, 2013
1 parent fcd761b commit 332a3c7
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Angular.js
Original file line number Diff line number Diff line change
Expand Up @@ -751,9 +751,10 @@ function toJsonReplacer(key, value) {
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
* @returns {string|undefined} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}

Expand Down
4 changes: 4 additions & 0 deletions test/AngularSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -879,5 +879,9 @@ describe('angular', function() {
it('should not serialize scope instances', inject(function($rootScope) {
expect(toJson({key: $rootScope})).toEqual('{"key":"$SCOPE"}');
}));

it('should serialize undefined as undefined', function() {
expect(toJson(undefined)).toEqual(undefined);
});
});
});

0 comments on commit 332a3c7

Please sign in to comment.