Skip to content

Commit

Permalink
Custom JSON parsing: return *all* unsafe integers as strings, even if…
Browse files Browse the repository at this point in the history
… numeric representation as string is the same
  • Loading branch information
jawj committed Jun 23, 2024
1 parent 6a886a9 commit c1ca79b
Showing 1 changed file with 3 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/db/customJSON.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ export function enableCustomJSONParsingForLargeNumbers(pg: typeof pgLib) {
pg.types.setTypeParser(pg.types.builtins.JSONB, parseJSONWithLargeNumbersAsStrings);
}

const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;

function parseJSONWithLargeNumbersAsStrings(str: string) {
return parse(str, undefined, function (k, str) {
const n = +str; // JSON parser ensures this is an ordinary number, parseInt(str, 10) not needed
if (n === Infinity || n === -Infinity) return str;
if ((n < MIN_SAFE_INTEGER || n > MAX_SAFE_INTEGER) && str.indexOf('.') === -1) return str;
if (str.length <= 15 || numericStringToExponential(str) === n.toExponential()) return n;
return str;
});
Expand Down

0 comments on commit c1ca79b

Please sign in to comment.