Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 7 additions & 0 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ var json_parse = function (options) {
);
}
}

_options.numberParser = options.numberParser;
}

var at, // The index of the current character
Expand Down Expand Up @@ -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');
Expand Down
10 changes: 10 additions & 0 deletions test/bigint-parse-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});