JSON.parse with context information on error
npx @tessl/cli install tessl/npm-json-parse-better-errors@1.0.0JSON 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.
npm install json-parse-better-errorsconst parseJson = require('json-parse-better-errors');const parseJson = require('json-parse-better-errors');
// Normal JSON parsing (same as JSON.parse)
const data = parseJson('{"name": "Alice", "age": 30}');
console.log(data); // { name: 'Alice', age: 30 }
// Enhanced error messages for malformed JSON
try {
parseJson('{"name": "Alice", "age":}'); // missing value
} catch (error) {
console.log(error.message);
// "Unexpected token } in JSON at position 20 while parsing near '{"name": "Alice", "age":}'"
}
// Control context length for error messages
try {
parseJson('invalid json here', null, 5);
} catch (error) {
console.log(error.message);
// "Unexpected token i in JSON at position 0 while parsing near 'inval...'"
}Parses JSON strings with the same API as JSON.parse() but provides enhanced error messages with contextual information when parsing fails.
/**
* Parse JSON string with enhanced error messages
* @param {string} txt - The JSON string to parse
* @param {function} [reviver] - Optional reviver function (same as JSON.parse)
* @param {number} [context=20] - Number of characters to show around error position
* @returns {any} The parsed JavaScript value
* @throws {SyntaxError} Enhanced syntax error with context information
* @throws {TypeError} Type error for non-string inputs
*/
function parseJson(txt, reviver, context);Parameters:
txt (required): The JSON string to parse, or other value to attempt parsingreviver (optional): A function that transforms the results, identical to the reviver parameter of JSON.parse()context (optional, default: 20): Number of characters to show around the error position in error messagesReturn Value:
JSON.parse())SyntaxError or TypeErrorEnhanced Error Types:
SyntaxError Enhancement: For malformed JSON, adds contextual snippet showing the problematic area
"Original error message while parsing near '...context...'"context parameterTypeError for Invalid Inputs:
undefined input: "Cannot parse undefined""Cannot parse [object Type]""Cannot parse an empty array"Usage Examples:
// With reviver function
const result = parseJson('{"date": "2023-01-01"}', (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
// Custom context length for shorter error messages
try {
parseJson('{"incomplete": ', null, 10);
} catch (error) {
// Error shows only 10 characters of context around the error
}
// Handling different input types
try {
parseJson(undefined);
} catch (error) {
console.log(error.message); // "Cannot parse undefined"
}
try {
parseJson([]);
} catch (error) {
console.log(error.message); // "Cannot parse an empty array"
}