1 | # parse-json
|
2 |
|
3 | > Parse JSON with more helpful errors
|
4 |
|
5 | ## Install
|
6 |
|
7 | ```sh
|
8 | npm install parse-json
|
9 | ```
|
10 |
|
11 | ## Usage
|
12 |
|
13 | ```js
|
14 | import parseJson, {JSONError} from 'parse-json';
|
15 |
|
16 | const json = '{\n\t"foo": true,\n}';
|
17 |
|
18 |
|
19 | JSON.parse(json);
|
20 | /*
|
21 | undefined:3
|
22 | }
|
23 | ^
|
24 | SyntaxError: Unexpected token }
|
25 | */
|
26 |
|
27 |
|
28 | parseJson(json);
|
29 | /*
|
30 | JSONError: 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 |
|
39 | parseJson(json, 'foo.json');
|
40 | /*
|
41 | JSONError: 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
|
51 | try {
|
52 | parseJson(json);
|
53 | } catch (error) {
|
54 | if (error instanceof JSONError) {
|
55 | error.fileName = 'foo.json';
|
56 | }
|
57 |
|
58 | throw error;
|
59 | }
|
60 | /*
|
61 | JSONError: 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 |
|
74 | Throws a `JSONError` when there is a parsing error.
|
75 |
|
76 | #### string
|
77 |
|
78 | Type: `string`
|
79 |
|
80 | #### reviver
|
81 |
|
82 | Type: `Function`
|
83 |
|
84 | Prescribes 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 |
|
89 | Type: `string`
|
90 |
|
91 | The filename displayed in the error message.
|
92 |
|
93 | ### JSONError
|
94 |
|
95 | Exposed for `instanceof` checking.
|
96 |
|
97 | #### fileName
|
98 |
|
99 | Type: `string`
|
100 |
|
101 | The filename displayed in the error message.
|
102 |
|
103 | #### codeFrame
|
104 |
|
105 | Type: `string`
|
106 |
|
107 | The printable section of the JSON which produces the error.
|
108 |
|
109 | #### rawCodeFrame
|
110 |
|
111 | Type: `string`
|
112 |
|
113 | The raw version of `codeFrame` without colors.
|