1.0.0 ⢠Published 3 years ago
@jcbhmr/json-parse-better-error v1.0.0
JSON.parse()
better error
ā Better error metadata for JSON.parse()
š§āāļø Adds .filename
, .lineno
, and .colno
properties to the SyntaxError
\
āļø Just 370 bytes minzipped \
š» Works in Node.js and the browser!
Installation
npm install @jcbhmr/json-parse-better-error
import "https://esm.sh/@jcbhmr/json-parse-better-error";
Usage
ā ļø If no btoa()
function exists (if you're using Node.js v14) this module will
auto-import a global polyfill for it
import "@jcbhmr/json-parse-better-error/global";
import { JSON_parse } from "@jcbhmr/json-parse-better-error";
import "@jcbhmr/json-parse-better-error/global";
JSON.parse(`{ "this is malformed": }`);
// ā Uncaught
// SyntaxError: Unexpected token } in JSON at position 23
// {
// filename: 'data:application/json;base64,eyAidGhpcyBpcyBtYWxmb3JtZWQiOiB9',
// lineno: 1,
// colno: 24
// }
import { JSON_parse } from "@jcbhmr/json-parse-better-error";
// const userInput = myInput.value;
const userInput = `{ "this is invalid": 4.4.4 }`;
let userJSON;
try {
userJSON = JSON_parse(userInput);
} catch (error) {
const sourceLine = userInput.split(/\r?\n/g)[error.lineno - 1];
const pointerLine = " ".repeat(error.colno - 1) + "^ " + error.message;
alert(sourceLine + "\n" + pointerLine);
}
// { "this is invalid": 4.4.4 }
// ^ Unexpected token . in JSON at position 24
Prior art
1.0.0
3 years ago