@stackline/parse-json
Parse JSON with more helpful errors.
Documentation | npm | Issues | Repository
Current package version: 1.0.2
Why this package?
@stackline/parse-json is the Stackline-maintained distribution of parse-json@6.0.2. It is an independent continuation of parse-json; original authors and licenses remain credited below.
Compatibility
| Item | Value |
|---|---|
| Package | @stackline/parse-json@1.0.2 |
| API target | parse-json@6.0.2 |
| Supported Node.js | ^12.20.0 || ^14.13.1 || >=16.0.0 |
| License | MIT |
| Module type | module |
| Runtime dependencies | @babel/code-frame, error-ex, json-parse-even-better-errors, lines-and-columns |
Installation
npm install @stackline/parse-json
Preserve existing imports and plugin resolution with an npm alias:
npm install parse-json@npm:@stackline/parse-json
Usage and API reference
Parse JSON with more helpful errors
Install
npm install @stackline/parse-json
Usage
import parseJson from '@stackline/parse-json';
const json = '{\n\t"foo": true,\n}';
JSON.parse(json);
/*
undefined:3
}
^
SyntaxError: Unexpected token }
*/
parseJson(json);
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}'
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
parseJson(json, 'foo.json');
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
// You can also add the filename at a later point
try {
parseJson(json);
} catch (error) {
if (error instanceof parseJson.JSONError) {
error.fileName = 'foo.json';
}
throw error;
}
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
API
parseJson(string, reviver?, filename?)
Throws a JSONError when there is a parsing error.
string
Type: string
reviver
Type: Function
Prescribes how the value originally produced by parsing is transformed, before being returned. See JSON.parse docs for more.
filename
Type: string
The filename displayed in the error message.
parseJson.JSONError
Exposed for instanceof checking.
fileName
Type: string
The filename displayed in the error message.
codeFrame
Type: string
The printable section of the JSON which produces the error.
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.
Credits and original authors
- Original project: parse-json.
- Sindre Sorhus.
- Stackline maintenance: Alexandro Paixao Marques and Stackline contributors.
Original copyright, license notices and contributor acknowledgements remain part of this distribution. Stackline maintenance does not replace authorship of the original work.
License
MIT. See the license and notice files in the repository.
Community and Links
Use this repository's issue tracker for reproducible bugs and feature requests. Join r/Stackline for examples, usage questions and release discussions.