1.0.0 • Published 3 years ago

@jcbhmr/json-parse-better-error v1.0.0

Weekly downloads
-
License
-
Repository
-
Last release
3 years ago

JSON.parse() better error

ā›” Better error metadata for JSON.parse()

npm.io

šŸ§™ā€ā™‚ļø Adds .filename, .lineno, and .colno properties to the SyntaxError \ āš–ļø Just 370 bytes minzipped \ šŸ’» Works in Node.js and the browser!

Installation

npm jsDelivr

npm install @jcbhmr/json-parse-better-error
import "https://esm.sh/@jcbhmr/json-parse-better-error";

Usage

Node.js Deno HTML5

āš ļø 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