Skip to content

gotocartik/safe-json-parse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

parseguard

npm npm npm version license

A lightweight utility that safely parses JSON without crashing applications. Supports fallback values, error logging, and required field validation.

Installation

npm install parseguard

Usage

import parse from "parseguard";

const data = parse('{"name":"Karthik"}');
console.log(data.name); // "Karthik"

Fallback

Return a default value when JSON is invalid:

const data = parse("bad json", { fallback: {} });
// {}

Error Logging

Log parse errors to the console:

parse("bad json", { logError: true });
// [parseguard] Invalid JSON: Unexpected token

Required Field Validation

Ensure certain fields exist in the parsed object:

const data = parse('{"id":1}', {
  required: ["id", "email"],
  fallback: null,
});
// null — "email" is missing

Combined with logging:

const data = parse('{"id":1}', {
  required: ["id", "email"],
  fallback: { error: true },
  logError: true,
});
// [parseguard] Missing required fields: email
// { error: true }

Browser localStorage

Safely parse values from localStorage:

import parse from "parseguard";

localStorage.setItem("user", '{"name":"Alice"}');
const user = parse.storage("user");
// { name: "Alice" }

const missing = parse.storage("nonexistent", {});
// {}

API

parse(json, options?)

Param Type Default Description
json string required JSON string to parse
options object {} See options below

Options

Option Type Default Description
fallback any null Value returned on parse failure
logError boolean false Log parse/validation errors to console
required string[] [] Required field keys to validate

parse.storage(key, fallback?)

Safely parse a JSON value from localStorage.

Test

node test.js

License

MIT

About

A lightweight utility that safely parses JSON without crashing applications. Supports fallback values, error logging, and required field validation.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors