File tree Expand file tree Collapse file tree 2 files changed +19
-7
lines changed
Expand file tree Collapse file tree 2 files changed +19
-7
lines changed Original file line number Diff line number Diff line change @@ -6,7 +6,7 @@ module.exports = function (obj, opts) {
66 var space = opts . space || '' ;
77 if ( typeof space === 'number' ) space = Array ( space + 1 ) . join ( ' ' ) ;
88 var cycles = ( typeof opts . cycles === 'boolean' ) ? opts . cycles : false ;
9-
9+
1010 var cmp = opts . cmp && ( function ( f ) {
1111 return function ( node ) {
1212 return function ( a , b ) {
@@ -16,12 +16,15 @@ module.exports = function (obj, opts) {
1616 } ;
1717 } ;
1818 } ) ( opts . cmp ) ;
19-
19+
2020 var seen = [ ] ;
2121 return ( function stringify ( node , level ) {
2222 var indent = space ? ( '\n' + new Array ( level + 1 ) . join ( space ) ) : '' ;
2323 var colonSeparator = space ? ': ' : ':' ;
24-
24+
25+ if ( node && node . toJSON && typeof node . toJSON === 'function' ) {
26+ node = node . toJSON ( ) ;
27+ }
2528 if ( typeof node !== 'object' || node === null ) {
2629 return json . stringify ( node ) ;
2730 }
@@ -39,10 +42,7 @@ module.exports = function (obj, opts) {
3942 throw new TypeError ( 'Converting circular structure to JSON' ) ;
4043 }
4144 else seen . push ( node ) ;
42-
43- if ( node && node . toJSON && typeof node . toJSON === 'function' ) {
44- node = node . toJSON ( ) ;
45- }
45+
4646 var keys = objectKeys ( node ) . sort ( cmp && cmp ( node ) ) ;
4747 var out = [ ] ;
4848 for ( var i = 0 ; i < keys . length ; i ++ ) {
Original file line number Diff line number Diff line change @@ -6,3 +6,15 @@ test('toJSON function', function (t) {
66 var obj = { one : 1 , two : 2 , toJSON : function ( ) { return { one : 1 } ; } } ;
77 t . equal ( stringify ( obj ) , '{"one":1}' ) ;
88} ) ;
9+
10+ test ( 'toJSON returns string' , function ( t ) {
11+ t . plan ( 1 ) ;
12+ var obj = { one : 1 , two : 2 , toJSON : function ( ) { return 'one' ; } } ;
13+ t . equal ( stringify ( obj ) , '"one"' ) ;
14+ } ) ;
15+
16+ test ( 'toJSON returns array' , function ( t ) {
17+ t . plan ( 1 ) ;
18+ var obj = { one : 1 , two : 2 , toJSON : function ( ) { return [ 'one' ] ; } } ;
19+ t . equal ( stringify ( obj ) , '["one"]' ) ;
20+ } ) ;
You can’t perform that action at this time.
0 commit comments