3 ms·
Most good parsers have an option to parse to integers or arbitrary precision decimals.
by dtech 2y ago
Most good parsers have an option to parse to integers or arbitrary precision decimals.
- VMG 2y agoAgreed. Which means that Javascript does not have a good parser.
- exogen 2y ago`JSON.parse` actually does give you that option via the `reviver` parameter, which gives you access to the original string of digits (to pass to `BigInt` or the number type of your choosing) – so per this conversation fits the "good parser" criteria.
- whizzter 2y agoSadly the reviver parameter is a new invention only recently available in FF and Node, not at all in Safari. Naturally not that hard to write a custom JSON parser but the need itself is a bad thing.
- hajile 2y agoJust use the polyfill https://github.com/zloirock/core-js#jsonparse-source-text-access https://github.com/zloirock/core-js#jsonparse-source-text-ac...
- arnorhs 2y agoNo it's been there for ages. Finalized as part of ecmascript 5 What you are probably thinking of is the context parameter of the reviver callback. That is relatively recent and mostly a qol improvement
- whizzter 2y agoSorry yes, i was thinking of the context object with source parameter. The issue it solves is a big one though, since without it the JSON.parse functionality cannot parse numbers that are larger than 64bit float numbers (f.ex. bigints).
- hajile 2y agoTo be specific (if anyone was curious), you can force BigInt with something like this: //MAX_SAFE_INTEGER is actually 9007199254740991 which is 16 digits //you can instead check if exactly 16 and compare size one string digit at a time if absolute precision is desired. const bigIntReviver = (key, value, context) => typeof value === 'number' && Math.floor(value) === value && context.source.length > 15 ? BigInt(context.source) : value const jsonWithBigInt = x => JSON.parse(x, bigIntReviver) Generally, I'd rather throw if a number is unexpectedly too big otherwise you will mess up the types throughout the system (the field may not be monomorphic) and will outright fail if you try to use math functions not available to BigInts.
- VMG 2y agoHuh, TIL! https://caniuse.com/mdn-javascript_builtins_json_parse_reviver_parameter_context_argument https://caniuse.com/mdn-javascript_builtins_json_parse_reviv... Absent in Safari though