1 | 'use strict'
|
2 |
|
3 | module.exports = parseJson
|
4 | function parseJson (txt, reviver, context) {
|
5 | context = context || 20
|
6 | try {
|
7 | return JSON.parse(txt, reviver)
|
8 | } catch (e) {
|
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)
|
14 | }
|
15 | const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i)
|
16 | const errIdx = syntaxErr
|
17 | ? +syntaxErr[1]
|
18 | : e.message.match(/^Unexpected end of JSON.*/i)
|
19 | ? txt.length - 1
|
20 | : null
|
21 | if (errIdx != null) {
|
22 | const start = errIdx <= context
|
23 | ? 0
|
24 | : errIdx - context
|
25 | const end = errIdx + context >= txt.length
|
26 | ? txt.length
|
27 | : errIdx + context
|
28 | e.message += ` while parsing near '${
|
29 | start === 0 ? '' : '...'
|
30 | }${txt.slice(start, end)}${
|
31 | end === txt.length ? '' : '...'
|
32 | }'`
|
33 | } else {
|
34 | e.message += ` while parsing '${txt.slice(0, context * 2)}'`
|
35 | }
|
36 | throw e
|
37 | }
|
38 | }
|