Line data Source code
1 : /**
2 : * Parse JSON that may contain bare `NaN`/`Infinity`/`-Infinity` tokens
3 : * (which Python's `json.dumps` emits) by replacing them with `null` on
4 : * fallback. Coercion is lossy; a one-time warning is logged when it fires.
5 : */
6 1077 : export function parseJsonWithNonFinite<T = unknown>(
7 : text: string & { readonly parsedType?: T }
8 : ): T {
9 1077 : try {
10 1077 : return JSON.parse(text) as T
11 : } catch {
12 9 : return JSON.parse(replaceNonFiniteTokens(text)) as T
13 : }
14 : }
15 :
16 : // Match a JSON string OR a non-finite token outside string.
17 : // - `"(?:\\.|[^"\\])*"` a quoted string - matched first so anything that
18 : // looks like a token inside a string is skipped
19 : // - `(?<![\w.-])` skip non bare tokens (e.g. 1NaN)
20 : // - `(-?Infinity|NaN)` capture the non-finite token
21 : // - `(?![\w.])` skip non bare suffix tokens (e.g. NaN1)
22 2356 : const NON_FINITE_TOKEN =
23 : /"(?:\\.|[^"\\])*"|(?<![\w.-])(-?Infinity|NaN)(?![\w.])/g
24 :
25 9 : function replaceNonFiniteTokens(text: string): string {
26 9 : let hasWarned = false
27 9 : return text.replace(NON_FINITE_TOKEN, (match, token) => {
28 72 : if (token) {
29 18 : if (!hasWarned) {
30 9 : console.warn(
31 : 'JSON contained non-finite numeric tokens (NaN/Infinity); they were replaced with null.'
32 : )
33 9 : hasWarned = true
34 : }
35 18 : return 'null'
36 : }
37 54 : return match
38 : })
39 : }
|