2017-12-15 18:56:14 +00:00
|
|
|
'use strict';
|
2021-05-08 12:39:21 +00:00
|
|
|
const errorEx = require('error-ex');
|
|
|
|
const fallback = require('json-parse-even-better-errors');
|
|
|
|
const {default: LinesAndColumns} = require('lines-and-columns');
|
|
|
|
const {codeFrameColumns} = require('@babel/code-frame');
|
2017-12-15 18:56:14 +00:00
|
|
|
|
2021-05-08 12:39:21 +00:00
|
|
|
const JSONError = errorEx('JSONError', {
|
|
|
|
fileName: errorEx.append('in %s'),
|
|
|
|
codeFrame: errorEx.append('\n\n%s\n')
|
2017-12-15 18:56:14 +00:00
|
|
|
});
|
|
|
|
|
2021-05-08 12:39:21 +00:00
|
|
|
const parseJson = (string, reviver, filename) => {
|
2017-12-15 18:56:14 +00:00
|
|
|
if (typeof reviver === 'string') {
|
|
|
|
filename = reviver;
|
|
|
|
reviver = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
try {
|
2021-05-08 12:39:21 +00:00
|
|
|
return JSON.parse(string, reviver);
|
|
|
|
} catch (error) {
|
|
|
|
fallback(string, reviver);
|
|
|
|
throw error;
|
2017-12-15 18:56:14 +00:00
|
|
|
}
|
2021-05-08 12:39:21 +00:00
|
|
|
} catch (error) {
|
|
|
|
error.message = error.message.replace(/\n/g, '');
|
|
|
|
const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/);
|
2017-12-15 18:56:14 +00:00
|
|
|
|
2021-05-08 12:39:21 +00:00
|
|
|
const jsonError = new JSONError(error);
|
2017-12-15 18:56:14 +00:00
|
|
|
if (filename) {
|
2021-05-08 12:39:21 +00:00
|
|
|
jsonError.fileName = filename;
|
2017-12-15 18:56:14 +00:00
|
|
|
}
|
|
|
|
|
2021-05-08 12:39:21 +00:00
|
|
|
if (indexMatch && indexMatch.length > 0) {
|
|
|
|
const lines = new LinesAndColumns(string);
|
|
|
|
const index = Number(indexMatch[1]);
|
|
|
|
const location = lines.locationForIndex(index);
|
|
|
|
|
|
|
|
const codeFrame = codeFrameColumns(
|
|
|
|
string,
|
|
|
|
{start: {line: location.line + 1, column: location.column + 1}},
|
|
|
|
{highlightCode: true}
|
|
|
|
);
|
|
|
|
|
|
|
|
jsonError.codeFrame = codeFrame;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw jsonError;
|
2017-12-15 18:56:14 +00:00
|
|
|
}
|
|
|
|
};
|
2021-05-08 12:39:21 +00:00
|
|
|
|
|
|
|
parseJson.JSONError = JSONError;
|
|
|
|
|
|
|
|
module.exports = parseJson;
|