UNPKG

1.77 kBMarkdownView Raw
1# parse-json
2
3> Parse JSON with more helpful errors
4
5## Install
6
7```sh
8npm install parse-json
9```
10
11## Usage
12
13```js
14import parseJson, {JSONError} from 'parse-json';
15
16const json = '{\n\t"foo": true,\n}';
17
18
19JSON.parse(json);
20/*
21undefined:3
22}
23^
24SyntaxError: Unexpected token }
25*/
26
27
28parseJson(json);
29/*
30JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}'
31
32 1 | {
33 2 | "foo": true,
34> 3 | }
35 | ^
36*/
37
38
39parseJson(json, 'foo.json');
40/*
41JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
42
43 1 | {
44 2 | "foo": true,
45> 3 | }
46 | ^
47*/
48
49
50// You can also add the filename at a later point
51try {
52 parseJson(json);
53} catch (error) {
54 if (error instanceof JSONError) {
55 error.fileName = 'foo.json';
56 }
57
58 throw error;
59}
60/*
61JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
62
63 1 | {
64 2 | "foo": true,
65> 3 | }
66 | ^
67*/
68```
69
70## API
71
72### parseJson(string, reviver?, filename?)
73
74Throws a `JSONError` when there is a parsing error.
75
76#### string
77
78Type: `string`
79
80#### reviver
81
82Type: `Function`
83
84Prescribes how the value originally produced by parsing is transformed, before being returned. See [`JSON.parse` docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter
85) for more.
86
87#### filename
88
89Type: `string`
90
91The filename displayed in the error message.
92
93### JSONError
94
95Exposed for `instanceof` checking.
96
97#### fileName
98
99Type: `string`
100
101The filename displayed in the error message.
102
103#### codeFrame
104
105Type: `string`
106
107The printable section of the JSON which produces the error.
108
109#### rawCodeFrame
110
111Type: `string`
112
113The raw version of `codeFrame` without colors.