diff --git a/src/extended_json.ts b/src/extended_json.ts index e38cb06e..a8fe192f 100644 --- a/src/extended_json.ts +++ b/src/extended_json.ts @@ -213,7 +213,7 @@ function serializeValue(value: any, options: EJSONSerializeOptions): any { : { $date: { $numberLong: value.getTime().toString() } }; } - if (typeof value === 'number' && !options.relaxed) { + if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) { // it's an integer if (Math.floor(value) === value) { const int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, diff --git a/test/node/extended_json_tests.js b/test/node/extended_json_tests.js index c47d6fb5..926a242d 100644 --- a/test/node/extended_json_tests.js +++ b/test/node/extended_json_tests.js @@ -168,6 +168,15 @@ describe('Extended JSON', function () { expect(serialized).to.equal('42'); }); + it('should correctly serialize non-finite numbers', function () { + const numbers = { neginf: -Infinity, posinf: Infinity, nan: NaN }; + const serialized = EJSON.stringify(numbers); + expect(serialized).to.equal( + '{"neginf":{"$numberDouble":"-Infinity"},"posinf":{"$numberDouble":"Infinity"},"nan":{"$numberDouble":"NaN"}}' + ); + expect(EJSON.parse(serialized)).to.deep.equal(numbers); + }); + it('should correctly parse null values', function () { expect(EJSON.parse('null')).to.be.null; expect(EJSON.parse('[null]')[0]).to.be.null;