source: trip-planner-front/node_modules/parse-json/index.js@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.3 KB
RevLine 
[6a3a178]1'use strict';
2const errorEx = require('error-ex');
3const fallback = require('json-parse-even-better-errors');
4const {default: LinesAndColumns} = require('lines-and-columns');
5const {codeFrameColumns} = require('@babel/code-frame');
6
7const JSONError = errorEx('JSONError', {
8 fileName: errorEx.append('in %s'),
9 codeFrame: errorEx.append('\n\n%s\n')
10});
11
12const parseJson = (string, reviver, filename) => {
13 if (typeof reviver === 'string') {
14 filename = reviver;
15 reviver = null;
16 }
17
18 try {
19 try {
20 return JSON.parse(string, reviver);
21 } catch (error) {
22 fallback(string, reviver);
23 throw error;
24 }
25 } catch (error) {
26 error.message = error.message.replace(/\n/g, '');
27 const indexMatch = error.message.match(/in JSON at position (\d+) while parsing/);
28
29 const jsonError = new JSONError(error);
30 if (filename) {
31 jsonError.fileName = filename;
32 }
33
34 if (indexMatch && indexMatch.length > 0) {
35 const lines = new LinesAndColumns(string);
36 const index = Number(indexMatch[1]);
37 const location = lines.locationForIndex(index);
38
39 const codeFrame = codeFrameColumns(
40 string,
41 {start: {line: location.line + 1, column: location.column + 1}},
42 {highlightCode: true}
43 );
44
45 jsonError.codeFrame = codeFrame;
46 }
47
48 throw jsonError;
49 }
50};
51
52parseJson.JSONError = JSONError;
53
54module.exports = parseJson;
Note: See TracBrowser for help on using the repository browser.