From 5672de6b8a9f55b2c7789a2516744337e81dc8c5 Mon Sep 17 00:00:00 2001 From: Mark Tse Date: Tue, 15 Dec 2020 14:44:37 -0500 Subject: [PATCH] feat: now allows a custom number parser to be passed as an option. --- README.md | 23 +++++++++++++++++++++++ lib/parse.js | 7 +++++++ test/bigint-parse-test.js | 10 ++++++++++ 3 files changed, 40 insertions(+) diff --git a/README.md b/README.md index e7335c7..e8d0483 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,29 @@ const user = JSONbig.parse('{ "__proto__": { "admin": true }, "id": 12345 }'); // => result is { id: 12345 } ``` +#### options.numberParser, function, default: built-in parser + +Pass in a custom parser whenever a numeric value is encountered. +When set, ignores `options.storeAsString`, `options.useNativeBigInt`, and `options.alwaysParseAsBig`. + +```js +let JSONbig = require('../index')({ + // append " abc" to every number value found + numberParser: str => str + " abc" +}); + +JSONbig.parse('{"big":92233720368547758070,"small":123}'); +// result is { big: "92233720368547758070 abc","small":"123 abc"} + +JSONbig = require('../index')({ + // convert every number value found into a BigInt + numberParser: str => BigInt(str) +}); + +JSONbig.parse('{"big":92233720368547758070,"small":123}'); +// result is { big: 92233720368547758070n,"small":123n} +``` + ### Links: - [RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt) diff --git a/lib/parse.js b/lib/parse.js index bb4e5eb..08e9fa0 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -130,6 +130,8 @@ var json_parse = function (options) { ); } } + + _options.numberParser = options.numberParser; } var at, // The index of the current character @@ -201,6 +203,11 @@ var json_parse = function (options) { next(); } } + + if(_options.numberParser) { + return _options.numberParser(string); + } + number = +string; if (!isFinite(number)) { error('Bad number'); diff --git a/test/bigint-parse-test.js b/test/bigint-parse-test.js index e9755ff..be4207b 100644 --- a/test/bigint-parse-test.js +++ b/test/bigint-parse-test.js @@ -56,4 +56,14 @@ describe("Testing native BigInt support: parse", function () { expect(output).to.equal(input); done(); }); + + it("Uses custom parser if provided", function(done) { + var JSONbig = require('../index')({ + numberParser: str => str + " 14eeda86-0b52-4c63-845f-4b0a60fb667b" + }); + var obj = JSONbig.parse(input); + var output = JSONbig.stringify(obj); + expect(output).to.equal('{"big":"92233720368547758070 14eeda86-0b52-4c63-845f-4b0a60fb667b","small":"123 14eeda86-0b52-4c63-845f-4b0a60fb667b"}'); + done(); + }); }); \ No newline at end of file