Skip to content

Commit bec87bd

Browse files
committed
Alias toJSON to toJS deeply.
ensure that when toJSON is called, that toJSON is called on all nested objects as well. This ensures that custom implementations behave as expected. Closes immutable-js#271
1 parent ba7d8fe commit bec87bd

File tree

6 files changed

+48
-23
lines changed

6 files changed

+48
-23
lines changed

__tests__/Conversion.ts

+11
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,17 @@ describe('Conversion', () => {
140140
expect(JSON.stringify(js)).toBe(JSON.stringify(immutableData));
141141
});
142142

143+
it('JSON.stringify() respects toJSON methods on values', () => {
144+
var Model = Immutable.Record({});
145+
Model.prototype.toJSON = function() { return 'model'; }
146+
expect(
147+
Immutable.Map({ a: new Model() }).toJS()
148+
).toEqual({ "a": {} });
149+
expect(
150+
JSON.stringify(Immutable.Map({ a: new Model() }))
151+
).toEqual('{"a":"model"}');
152+
});
153+
143154
it('is conservative with array-likes, only accepting true Arrays.', () => {
144155
expect(Immutable.fromJS({1: 2, length: 3})).is(
145156
Immutable.Map().set('1', 2).set('length', 3)

dist/immutable.d.ts

+2
Original file line numberDiff line numberDiff line change
@@ -1420,6 +1420,8 @@ declare module 'immutable' {
14201420
*
14211421
* `IndexedIterables`, and `SetIterables` become Arrays, while
14221422
* `KeyedIterables` become Objects.
1423+
*
1424+
* @alias toJSON
14231425
*/
14241426
toJS(): any;
14251427

dist/immutable.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -3357,6 +3357,11 @@ $traceurRuntime.defaultSuperCall = defaultSuperCall;
33573357
return value && typeof value.toJS === 'function' ? value.toJS() : value;
33583358
})).__toJS();
33593359
},
3360+
toJSON: function() {
3361+
return this.toSeq().map((function(value) {
3362+
return value && typeof value.toJSON === 'function' ? value.toJSON() : value;
3363+
})).__toJS();
3364+
},
33603365
toKeyedSeq: function() {
33613366
return new ToKeyedSequence(this, true);
33623367
},
@@ -3638,7 +3643,6 @@ $traceurRuntime.defaultSuperCall = defaultSuperCall;
36383643
var IterablePrototype = Iterable.prototype;
36393644
IterablePrototype[IS_ITERABLE_SENTINEL] = true;
36403645
IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
3641-
IterablePrototype.toJSON = IterablePrototype.toJS;
36423646
IterablePrototype.__toJS = IterablePrototype.toArray;
36433647
IterablePrototype.__toStringMapper = quoteString;
36443648
IterablePrototype.inspect = IterablePrototype.toSource = function() {

0 commit comments

Comments
 (0)