- Published on
How to parse JSON with helpful errors in JavaScript
- Authors
- Name
- Ashik Nesin
- @AshikNesin
If you're working with a large set of JSON strings and need to parse it, we know how complex it is to debug things if something goes wrong.
Generic error messages that we get from the build in JSON.parse
method might not be a good fit for that use case.
/*
undefined:3
}
^
SyntaxError: Unexpected token }
*/
Ever wondered about some easy way for this use case?
That's where parse-json node package comes in.
With the help of this, you'll be getting a better error message if you run into any error when parsing.
Like this:
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}'
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
Dependency
npm install parse-json
Usage
import parseJson from 'parse-json';
const json = '{\n\t"foo": true,\n}';
parseJson(json);
/*
JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}'
1 | {
2 | "foo": true,
> 3 | }
| ^
*/
Happy parsing JSON!