json-parse-even-better-errors
Advanced tools
Comparing version 2.0.1 to 2.1.0
30
index.js
'use strict' | ||
const hexify = char => { | ||
const h = char.charCodeAt(0).toString(16).toUpperCase() | ||
return '0x' + (h.length % 2 ? '0' : '') + h | ||
} | ||
const parseError = (e, txt, context) => { | ||
@@ -10,7 +15,12 @@ if (!txt) { | ||
} | ||
const badToken = e.message.match(/^Unexpected token.*position\s+(\d+)/i) | ||
const errIdx = badToken ? +badToken[1] | ||
const badToken = e.message.match(/^Unexpected token (.) .*position\s+(\d+)/i) | ||
const errIdx = badToken ? +badToken[2] | ||
: e.message.match(/^Unexpected end of JSON.*/i) ? txt.length - 1 | ||
: null | ||
const msg = badToken ? e.message.replace(/^Unexpected token ./, `Unexpected token ${ | ||
JSON.stringify(badToken[1]) | ||
} (${hexify(badToken[1])})`) | ||
: e.message | ||
if (errIdx !== null && errIdx !== undefined) { | ||
@@ -30,3 +40,3 @@ const start = errIdx <= context ? 0 | ||
return { | ||
message: e.message + ` while parsing ${near}'${slice}'`, | ||
message: msg + ` while parsing ${near}${JSON.stringify(slice)}`, | ||
position: errIdx, | ||
@@ -36,3 +46,3 @@ } | ||
return { | ||
message: e.message + ` while parsing '${txt.slice(0, context * 2)}'`, | ||
message: msg + ` while parsing '${txt.slice(0, context * 2)}'`, | ||
position: 0, | ||
@@ -59,7 +69,8 @@ } | ||
const parseJson = (txt, reviver, context) => { | ||
const parseText = stripBOM(txt) | ||
context = context || 20 | ||
try { | ||
return JSON.parse(txt, reviver) | ||
return JSON.parse(parseText, reviver) | ||
} catch (e) { | ||
if (typeof txt !== 'string') { | ||
if (typeof txt !== 'string' && !Buffer.isBuffer(txt)) { | ||
const isEmptyArray = Array.isArray(txt) && txt.length === 0 | ||
@@ -74,7 +85,12 @@ throw Object.assign(new TypeError( | ||
throw new JSONParseError(e, txt, context, parseJson) | ||
throw new JSONParseError(e, parseText, context, parseJson) | ||
} | ||
} | ||
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) | ||
// because the buffer-to-string conversion in `fs.readFileSync()` | ||
// translates it to FEFF, the UTF-16 BOM. | ||
const stripBOM = txt => String(txt).replace(/^\uFEFF/, '') | ||
module.exports = parseJson | ||
parseJson.JSONParseError = JSONParseError |
{ | ||
"name": "json-parse-even-better-errors", | ||
"version": "2.0.1", | ||
"version": "2.1.0", | ||
"description": "JSON.parse with context information on error", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
8048
78