Skip to content

Commit 5c4c402

Browse files
committed
Allow pretty-printing JSON output
1 parent fa9ae99 commit 5c4c402

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ assert(stringify('foo') === '"foo"');
2121
assert(stringify('foo\u2028bar\u2029baz') === '"foo\\u2028bar\\u2029baz"');
2222
assert(stringify(new Date('2014-12-19T03:42:00.000Z')) === 'new Date("2014-12-19T03:42:00.000Z")');
2323
assert(stringify({foo: 'bar'}) === '{"foo":"bar"}');
24+
assert(stringify({foo: 'bar'}, 4) === '{\n "foo": "bar"\n}');
25+
assert(stringify({foo: 'bar'}, '\t') === '{\n\t"foo": "bar"\n}');
2426
assert(stringify(undefined) === 'undefined');
2527
assert(stringify(null) === 'null');
2628
assert(

index.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
'use strict';
22

33
module.exports = stringify;
4-
function stringify(obj) {
4+
function stringify(obj, indentation) {
55
if (obj instanceof Date) {
66
return 'new Date(' + stringify(obj.toISOString()) + ')';
77
}
88
if (obj === undefined) {
99
return 'undefined';
1010
}
11-
return JSON.stringify(obj)
11+
return JSON.stringify(obj, undefined, indentation)
1212
.replace(/\u2028/g, '\\u2028')
1313
.replace(/\u2029/g, '\\u2029')
1414
.replace(/</g, '\\u003C')

test/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ assert(stringify('foo') === '"foo"');
77
assert(stringify('foo\u2028bar\u2029baz') === '"foo\\u2028bar\\u2029baz"');
88
assert(stringify(new Date('2014-12-19T03:42:00.000Z')) === 'new Date("2014-12-19T03:42:00.000Z")');
99
assert(stringify({foo: 'bar'}) === '{"foo":"bar"}');
10+
assert(stringify({foo: 'bar'}, undefined) === '{"foo":"bar"}');
11+
assert(stringify({foo: 'bar'}, 3) === '{\n "foo": "bar"\n}');
12+
assert(stringify({foo: 'bar'}, ' \t') === '{\n \t"foo": "bar"\n}');
1013
assert(stringify(undefined) === 'undefined');
1114
assert(stringify(null) === 'null');
1215
assert(

0 commit comments

Comments
 (0)