JSON.parse with context information on error
npx @tessl/cli install tessl/npm-json-parse-better-errors@1.0.00
# JSON Parse Better Errors
1
2
JSON Parse Better Errors provides an enhanced version of `JSON.parse()` that delivers more informative error messages when JSON parsing fails. When standard `JSON.parse()` encounters malformed JSON, it provides cryptic error messages that are difficult to debug. This library wraps `JSON.parse()` and catches parsing errors, then enhances them by adding contextual information including the position of the error within the JSON string and a snippet of the surrounding text that caused the parse failure.
3
4
## Package Information
5
6
- **Package Name**: json-parse-better-errors
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install json-parse-better-errors`
10
11
## Core Imports
12
13
```javascript
14
const parseJson = require('json-parse-better-errors');
15
```
16
17
## Basic Usage
18
19
```javascript
20
const parseJson = require('json-parse-better-errors');
21
22
// Normal JSON parsing (same as JSON.parse)
23
const data = parseJson('{"name": "Alice", "age": 30}');
24
console.log(data); // { name: 'Alice', age: 30 }
25
26
// Enhanced error messages for malformed JSON
27
try {
28
parseJson('{"name": "Alice", "age":}'); // missing value
29
} catch (error) {
30
console.log(error.message);
31
// "Unexpected token } in JSON at position 20 while parsing near '{"name": "Alice", "age":}'"
32
}
33
34
// Control context length for error messages
35
try {
36
parseJson('invalid json here', null, 5);
37
} catch (error) {
38
console.log(error.message);
39
// "Unexpected token i in JSON at position 0 while parsing near 'inval...'"
40
}
41
```
42
43
## Capabilities
44
45
### JSON Parsing with Enhanced Errors
46
47
Parses JSON strings with the same API as `JSON.parse()` but provides enhanced error messages with contextual information when parsing fails.
48
49
```javascript { .api }
50
/**
51
* Parse JSON string with enhanced error messages
52
* @param {string} txt - The JSON string to parse
53
* @param {function} [reviver] - Optional reviver function (same as JSON.parse)
54
* @param {number} [context=20] - Number of characters to show around error position
55
* @returns {any} The parsed JavaScript value
56
* @throws {SyntaxError} Enhanced syntax error with context information
57
* @throws {TypeError} Type error for non-string inputs
58
*/
59
function parseJson(txt, reviver, context);
60
```
61
62
**Parameters:**
63
64
- `txt` (required): The JSON string to parse, or other value to attempt parsing
65
- `reviver` (optional): A function that transforms the results, identical to the reviver parameter of `JSON.parse()`
66
- `context` (optional, default: 20): Number of characters to show around the error position in error messages
67
68
**Return Value:**
69
- On success: The parsed JavaScript object/value (identical to `JSON.parse()`)
70
- On error: Throws enhanced `SyntaxError` or `TypeError`
71
72
**Enhanced Error Types:**
73
74
1. **SyntaxError Enhancement**: For malformed JSON, adds contextual snippet showing the problematic area
75
- Format: `"Original error message while parsing near '...context...'"`
76
- Context shows surrounding characters based on `context` parameter
77
- Handles both "Unexpected token" and "Unexpected end of JSON input" errors
78
79
2. **TypeError for Invalid Inputs**:
80
- `undefined` input: `"Cannot parse undefined"`
81
- Non-string objects: `"Cannot parse [object Type]"`
82
- Empty arrays: `"Cannot parse an empty array"`
83
84
**Usage Examples:**
85
86
```javascript
87
// With reviver function
88
const result = parseJson('{"date": "2023-01-01"}', (key, value) => {
89
if (key === 'date') return new Date(value);
90
return value;
91
});
92
93
// Custom context length for shorter error messages
94
try {
95
parseJson('{"incomplete": ', null, 10);
96
} catch (error) {
97
// Error shows only 10 characters of context around the error
98
}
99
100
// Handling different input types
101
try {
102
parseJson(undefined);
103
} catch (error) {
104
console.log(error.message); // "Cannot parse undefined"
105
}
106
107
try {
108
parseJson([]);
109
} catch (error) {
110
console.log(error.message); // "Cannot parse an empty array"
111
}
112
```