Skip to content

Commit

Permalink
Allow pretty-printing JSON output
Browse files Browse the repository at this point in the history
  • Loading branch information
cspotcode committed Apr 13, 2017
1 parent fa9ae99 commit 5c4c402
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ assert(stringify('foo') === '"foo"');
assert(stringify('foo\u2028bar\u2029baz') === '"foo\\u2028bar\\u2029baz"');
assert(stringify(new Date('2014-12-19T03:42:00.000Z')) === 'new Date("2014-12-19T03:42:00.000Z")');
assert(stringify({foo: 'bar'}) === '{"foo":"bar"}');
assert(stringify({foo: 'bar'}, 4) === '{\n "foo": "bar"\n}');
assert(stringify({foo: 'bar'}, '\t') === '{\n\t"foo": "bar"\n}');
assert(stringify(undefined) === 'undefined');
assert(stringify(null) === 'null');
assert(
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use strict';

module.exports = stringify;
function stringify(obj) {
function stringify(obj, indentation) {
if (obj instanceof Date) {
return 'new Date(' + stringify(obj.toISOString()) + ')';
}
if (obj === undefined) {
return 'undefined';
}
return JSON.stringify(obj)
return JSON.stringify(obj, undefined, indentation)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/</g, '\\u003C')
Expand Down
3 changes: 3 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ assert(stringify('foo') === '"foo"');
assert(stringify('foo\u2028bar\u2029baz') === '"foo\\u2028bar\\u2029baz"');
assert(stringify(new Date('2014-12-19T03:42:00.000Z')) === 'new Date("2014-12-19T03:42:00.000Z")');
assert(stringify({foo: 'bar'}) === '{"foo":"bar"}');
assert(stringify({foo: 'bar'}, undefined) === '{"foo":"bar"}');
assert(stringify({foo: 'bar'}, 3) === '{\n "foo": "bar"\n}');
assert(stringify({foo: 'bar'}, ' \t') === '{\n \t"foo": "bar"\n}');
assert(stringify(undefined) === 'undefined');
assert(stringify(null) === 'null');
assert(
Expand Down

0 comments on commit 5c4c402

Please sign in to comment.