3 module.exports = parseJson
4 function parseJson (txt, reviver, context) {
5 context = context || 20
7 return JSON.parse(txt, reviver)
9 if (typeof txt !== 'string') {
10 const isEmptyArray = Array.isArray(txt) && txt.length === 0
11 const errorMessage = 'Cannot parse ' +
12 (isEmptyArray ? 'an empty array' : String(txt))
13 throw new TypeError(errorMessage)
15 const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
16 const errIdx = syntaxErr
18 : e.message.match(/^Unexpected end of JSON.*/i)
22 const start = errIdx <= context
25 const end = errIdx + context >= txt.length
28 e.message += ` while parsing near '${
29 start === 0 ? '' : '...'
30 }${txt.slice(start, end)}${
31 end === txt.length ? '' : '...'
34 e.message += ` while parsing '${txt.slice(0, context * 2)}'`