parse-json
Advanced tools
Comparing version
31
index.js
@@ -1,5 +0,6 @@ | ||
import fallback from 'json-parse-even-better-errors'; | ||
import {codeFrameColumns} from '@babel/code-frame'; | ||
import indexToPosition from 'index-to-position'; | ||
const getCodePoint = character => `\\u{${character.codePointAt(0).toString(16)}}`; | ||
export class JSONError extends Error { | ||
@@ -35,3 +36,3 @@ name = 'JSONError'; | ||
const getErrorLocation = (string, message) => { | ||
const match = message.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))? while parsing/); | ||
const match = message.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/); | ||
@@ -59,5 +60,11 @@ if (!match) { | ||
export default function parseJson(string, reviver, filename) { | ||
const addCodePointToUnexpectedToken = message => message.replace( | ||
// TODO[engine:node@>=20]: The token always quoted after Node.js 20 | ||
/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/, | ||
(_, _quote, token) => `"${token}"(${getCodePoint(token)})`, | ||
); | ||
export default function parseJson(string, reviver, fileName) { | ||
if (typeof reviver === 'string') { | ||
filename = reviver; | ||
fileName = reviver; | ||
reviver = undefined; | ||
@@ -73,16 +80,14 @@ } | ||
try { | ||
fallback(string, reviver); | ||
} catch (error) { | ||
message = error.message; | ||
let location; | ||
if (string) { | ||
location = getErrorLocation(string, message); | ||
message = addCodePointToUnexpectedToken(message); | ||
} else { | ||
message += ' while parsing empty string'; | ||
} | ||
message = message.replaceAll('\n', ''); | ||
const jsonError = new JSONError(message); | ||
if (filename) { | ||
jsonError.fileName = filename; | ||
} | ||
jsonError.fileName = fileName; | ||
const location = getErrorLocation(string, message); | ||
if (location) { | ||
@@ -89,0 +94,0 @@ jsonError.codeFrame = generateCodeFrame(string, location); |
{ | ||
"name": "parse-json", | ||
"version": "8.0.1", | ||
"version": "8.1.0", | ||
"description": "Parse JSON with more helpful errors", | ||
@@ -42,4 +42,3 @@ "license": "MIT", | ||
"@babel/code-frame": "^7.22.13", | ||
"index-to-position": "^0.1.1", | ||
"json-parse-even-better-errors": "^3.0.0", | ||
"index-to-position": "^0.1.2", | ||
"type-fest": "^4.7.1" | ||
@@ -46,0 +45,0 @@ }, |
9522
2.27%3
-25%180
1.69%- Removed
- Removed
Updated